5.4bash算術運算、位置參數和read

ARITHMETIC EVALUATION  算術運算
   The  shell  allows  arithmetic  expressions  to  be  evaluated, under certain circumstances (see the let and
   declare builtin commands and Arithmetic Expansion).  Evaluation is done  in  fixed-width  integers  with  no
   check for overflow, though division by 0 is trapped and flagged as an error.  The operators and their prece-
   dence, associativity, and values are the same as in the C language.  The  following  list  of  operators  is
   grouped into levels of equal-precedence operators.  The levels are listed in order of decreasing precedence.linux

   id++ id--
          variable post-increment and post-decrement
   ++id --id
          variable pre-increment and pre-decrement
   - +    unary minus and plus
   ! ~    logical and bitwise negation
   **     exponentiation
   * / %  multiplication, division, remainder
   + -    addition, subtraction
   << >>  left and right bitwise shifts
   <= >= < >
          comparison
   == !=  equality and inequality
   &      bitwise AND
   ^      bitwise exclusive OR
   |      bitwise OR
   &&     logical AND
   ||     logical OR
   expr?expr:expr
          conditional operator
   = *= /= %= += -= <<= >>= &= ^= |=
          assignment
   expr1 , expr2
          commagit

   Shell variables are allowed as operands; parameter expansion is performed before the  expression  is  evalu-
   ated.   Within  an  expression,  shell  variables may also be referenced by name without using the parameter
   expansion syntax.  A shell variable that is null or unset evaluates to 0 when  referenced  by  name  without
   using the parameter expansion syntax.  The value of a variable is evaluated as an arithmetic expression when
   it is referenced, or when a variable which has been given the integer attribute using declare -i is assigned
   a value.  A null value evaluates to 0.  A shell variable need not have its integer attribute turned on to be
   used in an expression.shell

   Constants with a leading 0 are interpreted as octal numbers.  A leading 0x or 0X denotes hexadecimal.   Oth-
   erwise,  numbers  take  the  form [base#]n, where base is a decimal number between 2 and 64 representing the
   arithmetic base, and n is a number in that base.  If base# is omitted, then base 10  is  used.   The  digits
   greater than 9 are represented by the lowercase letters, the uppercase letters, @, and _, in that order.  If
   base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably  to  represent
   numbers between 10 and 35.express

   Operators  are evaluated in order of precedence.  Sub-expressions in parentheses are evaluated first and may
   override the precedence rules above.bash

sum=5
sum=$[$sum+8]  同等  let sum+=8
[root@linux_basic ~]#sum=5
[root@linux_basic ~]#sum=$[$sum+8]
[root@linux_basic ~]#echo $sum
13
[root@linux_basic ~]#let sum+=7
[root@linux_basic ~]#echo $sum
20
練習:
a.計算100之內全部正整數之和
b.分別計算100之內全部偶數之和和奇數之和;
c.計算當前系統全部用戶的ID之和;
a.
sum=0
for n in {1..100}
do
  sum=$[$sum+$n]
done
 
echo "sum=$sum"app

bash下用來測試腳本
bash -n scriprs.sh
    用來單步執行腳本,用來調試的
    bash -x scripts.sh
從1開始步進爲2直到10結束  能夠獲得10之內的全部奇數   
[root@linux_basic scripts]#seq 1 2 10
1
3
5
7
9
從0開始步進爲2知道10結束  能夠獲得10之內的全部偶數
[root@linux_basic scripts]#seq 0 2 10
0
2
4
6
8
10less

b.
declare -i sum1=0
declare -i sum2=0
for n in $(seq 0 2 100)
do
    let sum+=$n
doneide

for n in $(seq 1 2 100)
do
    sum=$[$sum+$n]
donepost

echo "sum1=$sum1,sum2=$sum2"測試

c.
sum=0
for n in $(cut -d: -f3 /etc/passwd)
do
    let sum+=$n
done

echo "sum=$sum"

wc命令的使用
[root@linux_basic scripts]#type wc
wc is hashed (/usr/bin/wc)
[root@linux_basic scripts]#wc --help
Usage: wc [OPTION]... [FILE]...
  or:  wc [OPTION]... --files0-from=F
Print newline, word, and byte counts for each FILE, and a total line if
more than one FILE is specified.  With no FILE, or when FILE is -,
                                  後面跟文件,或者沒有文件時,讀取標準輸入
read standard input.
  -c, --bytes            print the byte counts  打印字節數
  -m, --chars            print the character counts 打印字符數
  -l, --lines            print the newline counts  打印行數
      --files0-from=F    read input from the files specified by
                           NUL-terminated names in file F;
                           If F is - then read names from standard input
  -L, --max-line-length  print the length of the longest line  打印最長行的長度
  -w, --words            print the word counts  打印單詞數
 
[root@linux_basic scripts]#wc -m /etc/rc.d/rc.sysinit /etc/init.d/functions /etc/issue
19914 /etc/rc.d/rc.sysinit
19295 /etc/init.d/functions
   47 /etc/issue
39256 total

練習:
a.計算/etc/rc.d/rc.sysinit,/etc/init.d/functions和/etc/issue三個文件的字符數之和;
b.新建用戶tmpuser1-tmpuser10,並計算他們的id之和;
a.
sum=0
for n in /etc/rc.d/rc.sysinit /etc/init.d/functions /etc/issue
do
   num=$(wc -m $n|cut -d' ' -f1)
   sum=$[$sum+$num]
done

echo "sum=$sum"  

b.
sum=0
for n in {1..10}
do
    useradd tmpuser$n
    num=$(grep "^tmpuser$n:" /etc/passwd | cut -d: -f3)  或者使用  num=$(id -u tmpuser$n)
    let sum+=$num
done

echo "sum=$sum"

知識點:位置參數
    位置參數:   
    ./scripts.sh  arg1 arg2 arg3
         $0:腳本自身名字  scripts.sh
         $1:腳本的第一個參數  arg1
[root@linux_basic scripts]#chmod +x pos.sh
[root@linux_basic scripts]#bash -n pos.sh
[root@linux_basic scripts]#./pos.sh 23 9
The sum in:32
[root@linux_basic scripts]#cat pos.sh
#!/bin/bash
#
echo "The sum in:$[$1+$2]"
    特殊變量:
       $#:位置參數的個數
       $@、$*:引用全部的位置參數
[root@linux_basic scripts]#./pos.sh 12 5
The sum in:17
2
12 5
12 5
[root@linux_basic scripts]#cat pos.sh
#!/bin/bash
#
echo "The sum in:$[$1+$2]"
echo "$#"
echo "$*"
echo "$@"

知識點:交互式腳本
[root@linux_basic scripts]#type read
read is a shell builtin
[root@linux_basic scripts]#help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
    Read a line from the standard input and split it into fields.
   
    Reads a single line from the standard input, or from file descriptor FD
    if the -u option is supplied.  The line is split into fields as with word
    splitting, and the first word is assigned to the first NAME, the second
    word to the second NAME, and so on, with any leftover words assigned to
    the last NAME.  Only the characters found in $IFS are recognized as word
    delimiters.
經常使用選項
-p prompt     輸出prompt字串的內容後,可在後面接着輸入
   output the string PROMPT without a trailing newline before
   attempting to read
-t timeout    在等待輸入的超時時間
    time out and return failure if a complete line of input is
        not read withint TIMEOUT seconds.  The value of the TMOUT
        variable is the default timeout.  TIMEOUT may be a
        fractional number.  If TIMEOUT is 0, read returns success only
        if input is available on the specified file descriptor.  The
        exit status is greater than 128 if the timeout is exceeded  

[root@linux_basic scripts]#read a b
12 10 23
[root@linux_basic scripts]#echo $a
12
[root@linux_basic scripts]#echo $b
10 23
[root@linux_basic scripts]#read a b
12 36
[root@linux_basic scripts]#echo $a
12
[root@linux_basic scripts]#echo $b
36

知識點:給變量以默認值
    varname=${varname:-value}
       若是varname不空,則其值不變;不然,varname值爲value       
[root@linux_basic scripts]#b=22
[root@linux_basic scripts]#echo $b
22
[root@linux_basic scripts]#b=${b:-90}
[root@linux_basic scripts]#echo $b
22
[root@linux_basic scripts]#unset b
[root@linux_basic scripts]#b=${b:-90}
[root@linux_basic scripts]#echo $b
90       

[root@linux_basic scripts]#cat read.sh
#!/bin/bash
#
read -t 5 -p "Enter a number:" num

num=${num:-9}
echo $num       
[root@linux_basic scripts]#./read.sh
Enter a number:9   等待了5秒都沒有給值  沒有給值,默認是不會換行
[root@linux_basic scripts]#./read.sh
Enter a number:90  在5秒以內給了值
90

練習: 經過鍵盤給定一個文件的路徑,來判斷文件內容的類型; read -p "Enter a file name:" filename file $filename 經過鍵盤給定一個目錄的路徑,沒有給定則默認爲‘/’,來判斷文件內容的類型; read  -t 5 -p "Enter a directory path:" pathname pathname=${pathname:-/} for name in $(ls $pathname) do     file $pathname$name done

相關文章
相關標籤/搜索