本文将持续记录在shell脚本编写过程中使用到的一些技巧和知识,跟大家一起分享!
set -e
- 在脚本中,使用set -e之后,只要在脚本中有命令的执行的退出吗不为0,那么就会退出整个脚本
#!/bin/sh
set -e
ls /test
echo "test"
- 执行结果如下:
[docker@docker tmp]$ sh demo.sh
ls: cannot access /test: No such file or directory
- 可见,ls /test 后面的语句不再执行了。
set -o pipefail
- 这个命令是在使用管道符“|”时,如何定义该命令输出的返回码,默认是最后一个管道符命令输出的返回值,如果设置了,那么返回码则为从右到左的第一个执行命令返回结果不为0的命令
#!/bin/sh
ls /test|echo "test"
echo $?
- 默认的脚本输出结果
[docker@docker tmp]$ sh demo.sh test
ls: cannot access /test: No such file or directory
0
- 可以看到,返回码为0,实际上这个返回码就是管道符最后一个命令echo "test"的返回码
- 如果设置了该选项那么结果会是如下
#!/bin/sh
set -o pipefail
ls /test|echo "test"
echo $?
[docker@docker tmp]$ sh demo.sh test
ls: cannot access /test: No such file or directory
2
- 此时返回码为2,实际上就是ls /test的非0返回码
set -o xtrace
- 在shell执行过程中,命令比较多的情况下,我们常常需要看看哪个命令执行了没有,从哪里到哪里是这个命令的输出,我们可以使用这个设置,有利于查看各个指令的运行输出,并且相关的变量已经替我们解析好了
#!/bin/sh
set -o xtrace
ls /test|echo "test"
echo $?
- 执行结果
+ ls /test
+ echo test
test
ls: cannot access /test: No such file or directory
+ echo 0
0
设置默认变量
- 在脚本中,我们常常需要定义变量,某些变量具有默认值,我们使用如下方式来设置会显得比较优雅
: ${DEFAULT:="default"}
日志记录
- 在脚本执行过程中,我们需要对一些输出日志进行记录和输出,以提供软件或运维故障排查,可以使用以下简易代码来进行日志输出格式化
myapp_log() {
local type="$1"; shift
printf '%s [%s] [Entrypoint]: %s\n' "$(date "+%Y-%m-%d %H:%M:%S")" "$type" "$*"
}
myapp_note() {
myapp_log Note "$@"
}
myapp_warn() {
myapp_log Warn "$@" >&2
}
myapp_error() {
myapp_log ERROR "$@" >&2
exit 1
}
- 测试代码
#!/bin/sh
# logging functions
myapp_log() {
local type="$1"; shift
printf '%s [%s] [Entrypoint]: %s\n' "$(date "+%Y-%m-%d %H:%M:%S")" "$type" "$*"
}
myapp_note() {
myapp_log Note "$@"
}
myapp_warn() {
myapp_log Warn "$@" >&2
}
myapp_error() {
myapp_log ERROR "$@" >&2
exit 1
}
myapp_note "This is a Note"
myapp_warn "This is a Warn"
myapp_error "This is a error and the process will quit!"
- 输出结果
2020-01-28
11:27:45 [Note] [Entrypoint]: This is a Note
2020-01-28 11:27:45 [Warn] [Entrypoint]: This is a Warn
2020-01-28 11:27:45 [ERROR] [Entrypoint]: This is a error and the process will quit!
cat 文件写入
- 在docker,或者一些脚本中,我们需要对文件进行编写保存或者在没有vi等其他工具的时候,需要写入多行数据,我们可以通过cat命令进行写入
cat << EOF > /etc/ansible/hosts
> [hosts]
> 127.0.0.1
> EOF
监控日志输出
monitor() {
tail -F -n 0 $1 | while read line; do echo -e "$2: $line"; done
}
- 为日志添加前缀,类似于装饰器
创建临时文件或目录
mktemp //创建临时文件
mktemp -d //创建临时目录
访问变量指向的变量
$ my=my_var
$ my_var=demo
$ echo "${my}" //访问变量my
my_var
$ echo "${!my}" //访问变量my的变量,即my_var变量内容
demo
访问敏感变量
- 在shell脚本中,有些敏感变量如密码、数据库连接等,不能暴露在脚本中,此时我们可以用文件的方式,让shell来进行读取加载,实现的代码片段如下
# usage: file_env VAR [DEFAULT]
# as example: file_env 'MYSQL_PASSWORD' 'zabbix'
# (will allow for "$MYSQL_PASSWORD_FILE" to fill in the value of "$MYSQL_PASSWORD" from a file)
# unsets the VAR_FILE afterwards and just leaving VAR
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local defaultValue="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo "**** Both variables $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$defaultValue"
if [ "${!var:-}" ]; then
val="${!var}"
echo "** Using ${var} variable from ENV"
elif [ "${!fileVar:-}" ]; then
if [ ! -f "${!fileVar}" ]; then
echo "**** Secret file \"${!fileVar}\" is not found"
exit 1
fi
val="$(< "${!fileVar}")"
echo "** Using ${var} variable from secret file"
fi
export "$var"="$val"
unset "$fileVar"
}
命令替换
- 在shell中,我们经常需要对一些命令的结果进行输出后,再送到命令行进行命令执行,此时我们需要使用命令替换的方式,这里有两种方式,基本是等价的,但是在有些shell解释器中,可能不支持。
shell扫描一遍命令行,发现了$(cmd)结构或者`command`结构,便将$(cmd)中或`command`的cmd执行一次,得到其标准输出,再将此输出放到原来命令。有些shell不支持,如tcsh。 - 示例
# echo $(pwd)
/root
# echo `pwd`
/root
变量特性
-
在shell中,可以将一个具有多行内容赋值给变量,但在变量存储过程中,会将多行符进行替换为空格
-
示例
# cat /tmp/test
test1
test2
test3
test4
- 通过替换变量,我们可以将该文件的读取结果赋值给一个变量,并进行输出
# echo $(cat /tmp/test)
test1 test2 test3 test4
- 这里还有个小技巧,可以直接使用 < 符号来实现文件内容读取
# echo $(< /tmp/test)
test1 test2 test3 test4
判断是否以某些字符开头或结尾
# first arg is `-f` or `--some-option`
# or first arg is `something.conf`
if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then
echo "Doing sth!!!"
fi
- 这里使用了变量的匹配模式 # 号为向左匹配,匹配到第一个#后面的字符为止并把变量进行赋值
- %为向右匹配,匹配到第一个% 后面的字符为止并把变量进行赋值
- 示例
[root@docker ~]# myvar="--help"
[root@docker ~]# echo ${myvar}
--help
[root@docker ~]# echo ${myvar%help}
--
[root@docker ~]# echo ${myvar#--}
help
设置shell代码是否调试
# Script trace mode
if [ "${DEBUG_MODE}" == "true" ]; then
set -o xtrace
fi
424


&spm=1001.2101.3001.11974&articleId=103891268&d=1&t=3&u=cf89703464b24be59de0da210533e1b3)

被折叠的 条评论
为什么被折叠?



