shell脚本安全实现之set命令

时间:2025-01-13 18:58:04

一、set命令作用

字符

作用

u

开启此项,在使用一个没有声明的变量时,会报错,并且终止程序,同 set -o nounset

e

开启此项,命令返回非0就退出,不再继续执行后面的代码,同 set -o errexit

o

set -o 显示所有; set -o option 开启 option 项; set +o option 关闭 option 项

x

set -x

  1. -u 在扩展一个没有设置的变量时,显示错误信息, 等同set -o nounset
  2. -e 如果一个命令返回一个非0退出状态值(失败)就退出, 等同set -o errexit
  3. -o option 显示,打开或者关闭选项 显示选项:set -o 打开选项:set -o 选项 关闭选项:set +o 选项
  4. -x 当执行命令时,打印命令及其参数,类似 bash -x

二、范例

[root@rocky ~]# set -o
allexport       off
braceexpand     on
emacs           on
errexit         off
errtrace        off
functrace       off
hashall         on
histexpand      on
history         on
ignoreeof       off
interactive-comments    on
keyword         off
monitor         on
noclobber       off
noexec          off
noglob          off
nolog           off
notify          off
nounset         off
onecmd          off
physical        off
pipefail        off
posix           off
privileged      off
verbose         off
vi              off
xtrace          off

范例1:限制使用没声明的变量

[root@rocky ~]# ll /test
ls: cannot access '/test': No such file or directory
[root@rocky ~]# tee > ~/test1.sh << EOF
#!/bin/bash
set -u
DIR=/test
rm -rf \${DIr}/* #这个变量其实不存在(/路径不存在test目录),如果没有set -u选项,则会删除根目录
EOF
[root@rocky ~]# sh test1.sh
test1.sh: 4: DIr: parameter not set
[root@rocky ~]# ls / #查看/,正常
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  script  srv  sys  tmp  usr  var

范例2:遇到错误即刻终止脚本

[root@rocky ~]# ls /test2
ls: cannot access '/test2': No such file or directory
[root@rocky ~]# tee > ~/test2.sh << EOF
#!/bin/bash
set -e
echo 123
cd /test2/ #这个目录不存在,如果没有set -e,则也会删当前工作目录
rm -rf *
echo 456
EOF
[root@rocky ~]# sh test2.sh 
123
test2.sh: 第 4 行:cd: /test2/: No such file or directory
[root@rocky ~]# ls
test1.sh  test2.sh