前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux中set命令设置位置参数

Linux中set命令设置位置参数

作者头像
qsjs
发布2020-06-09 10:34:46
4.5K0
发布2020-06-09 10:34:46
举报

set 是Linux 的内置命令,这是一个非常有用的命令,只是可能因为不熟悉,所以就不怎么用,如果你看一些比较成熟的shell scripts, 经常会看到用set的地方,本文对set命令的-e , — option 做一些简单讲解:

代码语言:javascript
复制
[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 则是取消这种设置; 看下面的例子:

代码语言:javascript
复制
[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来实现:

代码语言:javascript
复制
[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 ~]#

本文原创,转载请注明出处.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档