shell的set有两个作用:
一个作用就是触发选项标志位来帮助决定脚本的行为..
set -x
打开脚本的调试模式,脚本在运行过程中先输出原来的命令,再输出命令执行后的结果。
set +x
“-”与“+”的区别在于一个是开启一个是关闭。这个在很多其他的命令里也是这样的用法。
另一个应用就是以一个命令的结果(set `command`)来重新设置脚本的位置参数.脚本将会从命令的输出中重新分析出位置参数.
echo "Positional parameters before set\`uname -a\` :"
echo "Command-line argument #1 = $1"
echo "Command-line argument #2 = $2"
echo "Command-line argument #3 = $3"
set `uname -a` # 把`uname -a`的命令输出设置为新的位置参数。
echo "Positional parameters after set\`uname -a\` :"
# $1, $2, $3, 等等. 这些位置参数将被重新初始化为`uname -a`的结果
echo "Field #1 of 'uname -a' = $1"
echo "Field #2 of 'uname -a' = $2"
echo "Field #3 of 'uname -a' = $3"
exit 0
调用以上脚本./set-test.sh one two three
Positional parameters before set `uname -a`: #正常的输出参数
Command-line argument #1 = one
Command-line argument #2 = two
Command-line argument #3 = three
Positional parameters after set `uname -a`: #使用set命令,把命令uname -a的输出值替换到变量$1 $2 $3 ... 于是打印的结果就改变了
Field #1 of 'uname -a' = Linux
Field #2 of 'uname -a' = localhost.localdomain
Field #3 of 'uname -a' = 2.6.32-220.el6.i686