您的位置:首页 > 运维架构 > Shell

5.4bash算术运算、位置参数和read

2016-04-22 00:00 585 查看
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.

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
comma

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.

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.

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

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"

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
10

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

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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: