shell编程之算术扩展(引号、命令替换、算术扩展)

1、单引号 、双引号、反引号的区别

单引号:忽略所有特殊字符

双引号:忽略大部分特殊字符($  `等字符除外)

[root@tlinux shell]# echo '*'
*
[root@tlinux shell]# echo *          输出目录下所有文件
02.sh 03.sh o1hello.sh text.sh
[root@tlinux shell]# x
=* [root@tlinux shell]# echo $x 02.sh 03.sh o1hello.sh text.sh [root@tlinux shell]# echo "$x" * [root@tlinux shell]# echo '$x' 忽略所有特殊字符 $x

反引号:命令替换(将一个命令的标准输出插入到命令的任何位置)

$(): 同样是命令替换

命令替换可以嵌套(如果使用反引号,则内部的反引号必须用反斜杠来转义)  :echo  `basename \`pwd\``       echo $(basename $(pwd))

basename 命令:求路径中最后一项名称

dirname 命令:求路径中路径前面的名称

[root@tlinux shell]# echo `pwd`
/shell
[root@tlinux shell]# echo $(pwd)
/shell
[root@tlinux shell]# basename /hh/aa
aa
[root@tlinux shell]# dirname /hh/aa/bb
/hh/aa
\[root@tlinux shell]# basename  `pwd`
shell
[root@tlinux shell]# dirname `pwd`
/
[root@tlinux shell]# echo `basename \`pwd\``
shell
[root@tlinux shell]# echo $(basename $(pwd))
shell

2、算术运算符

基本算术运算符与C语言一模一样

算术扩展:$[] 

[root@tlinux shell]# n=5;echo $[$n+1]
6
[root@tlinux shell]# echo n+1
n+1
[root@tlinux shell]# echo $n+1
5+1

$(())等价于$[]  

[root@tlinux shell]# echo $(($n+2))
7
[root@tlinux shell]# echo $(($n*2))
10

(()) :整体表达式 不可赋值   是一个独立的语句

[root@tlinux shell]# ((n+=1))
[root@tlinux shell]# echo $n
6
[root@tlinux shell]# echo ((n+=1))
bash: syntax error near unexpected token `('
[root@tlinux shell]# r=((n+=1))
bash: syntax error near unexpected token `('
[root@tlinux shell]# r=$[$n+1]
[root@tlinux shell]# echo $r
7

expr  :符号两边一定要有空格

[root@tlinux shell]# expr 4 + 5
9
[root@tlinux shell]# r= `expr 4 * 5`
expr: syntax error
[root@tlinux shell]# r=`expr 4 \* 5`   *对shell有特殊含义  echo   $*
[root@tlinux shell]# echo $r
20

let  是shell内置命令

[root@tlinux shell]# let n=n+_1
[root@tlinux shell]# 
[root@tlinux shell]# let n=n+1
[root@tlinux shell]# echo $n
6
[root@tlinux shell]# let "n= n+ 1"
[root@tlinux shell]# echo $n
7
[root@tlinux shell]# let n=n +1
[root@tlinux shell]# echo $n
7
[root@tlinux shell]# let n= n +1
bash: let: n=: syntax error: operand expected (error token is "=")
[root@tlinux shell]# let "n= n+1"
[root@tlinux shell]# echo $n
8

 

posted on 2019-05-05 20:55  wsw_seu  阅读(271)  评论(0编辑  收藏  举报

导航