Linux中set命令設置位置參數


學習getopt 時對set 的設置命令行參數有疑問

#將規范化后的命令行參數分配至位置參數($1,$2,...)

eval set -- "${ARGS}"

 

轉載

作者:My熊貓眼
鏈接:https://www.jianshu.com/p/d7a59e20f249
來源:簡書

set 是Linux 的內置命令,這是一個非常有用的命令,只是可能因為不熟悉,所以就不怎么用,如果你看一些比較成熟的shell scripts, 經常會看到用set的地方,本文對set命令的-e , — option 做一些簡單講解:

[root@localhost bin]# help set | tail
The -x and -v options are turned off.

Using + rather than - causes these flags to be turned off. The
flags can also be used upon invocation of the shell. The current
set of flags may be found in $-. The remaining n ARGs are positional
parameters and are assigned, in order, to $1, $2, .. $n. If no
ARGs are given, all shell variables are printed.

Exit Status:
Returns success unless an invalid option is given.
[root@localhost bin]#
從上面set的幫助可以看到, “+” ,"-" 分別用於關閉或者打開某些特性;具體的特性有很多,這里介紹 -e 特性:
set -e ; 表示后續所有的bash 命令的返回code 如果不是0,那么腳本立即退出,后續的腳本將不會得到執行的機會;
set +e ; 這個是默認的狀態,表示就算后續的命令如果返回值不是0,那么腳本依然向下執行;
所以 set -e其實就是從設置的位置起,給腳本的每一條命令加上了同一個退出條件;而set +e 則是取消這種設置;
看下面的例子:

[root@localhost shell_commands]# cat test.sh
#!/bin/bash
function lookupstr(){
grep "sles" /etc/os-release >/dev/null 2>&1
if [ "$?" -ne 0 ];then
echo -e "Can not find the 'sles' string in file.\n"
fi
}

echo "Below results based on: set +e"
set +e
lookupstr

echo "Below results based on: set -e"
set -e
lookupstr
[root@localhost shell_commands]# ./test.sh
Below results based on: set +e
Can not find the 'sles' string in file.

Below results based on: set -e
[root@localhost shell_commands]#
set 除了上面的-e option 可以幫助優化腳本外,其"--" option 更有用:
在調用shell腳本的時候,通常傳遞參數給shell腳本,這些參數叫做位置參數,那么有沒有可能在沒有用shell腳本的時候也使用位置參數呢? 這時候就可以用 "--" option來實現:


[root@localhost ~]# help set
-- Assign any remaining arguments to the positional parameters.
If there are no remaining arguments, the positional parameters
are unset.
[root@localhost ~]#
[root@localhost ~]# echo $@
[root@localhost ~]# set -- p1 p2 -host -4
[root@localhost ~]# echo $@
p1 p2 -host -4
[root@localhost ~]# echo $1,$2,$3,$4
p1,p2,-host,-4
[root@localhost ~]#

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM