(4)shell替换

来源:互联网 发布:淘宝刷单被骗案例 编辑:程序博客网 时间:2024/06/06 12:57

1、shell转义字符(都可以使用在echo中):

shell转义字符
如果表达式中包含特殊字符,Shell 将会进行替换。

  1. -e 表示对转义字符进行替换
  2. 不使用 -e 选项,将会原样输出
  3. -E 选项禁止转义
  4. 默认也是不转义的
  5. -n 选项可以禁止插入换行符
#!/bin/basha=10echo -e "Value of a is $a \n"输出结果:Value of a is 10如果不使用-e,则会输出:Value of a is 10\n,也就是转移字符\n不会被替换。

2、命令替换:

命令替换是指Shell可以先执行命令,将输出结果暂时保存,在适当的地方输出。

使用语法:`command`注意:是反引号,不是单引号,这个键位于Esc键下方。
举例:#!/bin/bashDATE=`date`echo "Date is $DATE"USERS=`who | wc -l`echo "Logged in user are $USERS"UP=`date ; uptime`echo "Uptime is $UP"运行结果为:Date is Thu Jul  2 03:59:57 MST 2009Logged in user are 1Uptime is Thu Jul  2 03:59:57 MST 200903:59:57 up 20 days, 14:03,  1 user,  load avg: 0.13, 0.07, 0.15将命令date运行结果保存在变量DATE中,然后在echo中输出。

3、变量替换:

变量替换可以根据变量的状态(是否为空、是否定义等)来改变它的值。
可以使用变量替换形式为:
变量替换

#!/bin/bashecho ${var:-"Variable is not set"}echo "1 - Value of var is ${var}"#变量var没有定义,输出Variable is not set,且不改变var值,var为空#1 - Value of var isecho ${var:="Variable is not set"}echo "2 - Value of var is ${var}"#变量var没有定义,输出Variable is not set,且改变var值为Variable is not set#2 - Value of var is Variable is not setunset varecho ${var:+"This is default value"}echo "3 - Value of var is $var"#var已被unset,无输出,var为空#3 - Value of var isvar="Prefix"echo ${var:+"This is default value"}echo "4 - Value of var is $var"#var已被定义,因此输出This is default value#4 - Value of var is Prefixecho ${var:?"Print this message"}echo "5 - Value of var is ${var}"#var已经定义,因此输出var,Prefix#5 - Value of var is Prefix运行结果:Variable is not set1 - Value of var isVariable is not set2 - Value of var is Variable is not set3 - Value of var isThis is default value4 - Value of var is PrefixPrefix5 - Value of var is Prefix
0 0