Linux中set命令的部分用法

作者: My熊猫眼 | 来源:发表于2019-08-17 15:16 被阅读8次

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 ~]#

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

相关文章

  • Linux中set命令的部分用法

    set 是Linux 的内置命令,这是一个非常有用的命令,只是可能因为不熟悉,所以就不怎么用,如果你看一些比较成熟...

  • linux rename命令

    参考:Linux中rename命令的用法

  • Linux中less命令有什么作用?常用参数有哪些?

    Linux中less命令有什么作用?在Linux系统中,less命令的用法与more命令类似,它可以用来随意浏览文...

  • Linux常用命令

    Linux中wc命令用法 Linux系统中的wc(Word Count)命令的功能为统计指定文件中的字节数、字数、...

  • Linux:环境变量 - set、env、export

    Linux中set,env和export这三个命令的区别 set命令显示当前shell的变量,包括当前用户的变量;...

  • adb 实际工作高频用法

    adb 命令和 Linux 命令用法很相似,通过 adb shell 进入命令行后,用法基本和linux命令没有什...

  • DOS中SET命令的详细用法

    DOS中SET命令的详细用法 例子: 请看 set var=我是值 ,这就是BAT直接在批处理中设置变量的方法! ...

  • set命令详解

    linux set 命令 功能说明:设置shell。 语法:set [+-abCdefhHklmnpPtuvx]...

  • source命令

    Linux中source命令的用法 source命令: source命令也称为“点命令”,也就是一个点符号(.)。...

  • linux命令

    linux中 vi / vim显示行号或取消行号命令 显示行号:set number或者:set nu 取消行号显...

网友评论

    本文标题:Linux中set命令的部分用法

    本文链接:https://www.haomeiwen.com/subject/vrzhsctx.html