shell脚本中的${1#-}和${1%.conf}

在redis中的镜像看到这么一个脚本

cat /usr/local/bin/docker-entrypoint.sh 
#!/bin/sh
set -e

# first arg is `-f` or `--some-option`
# or first arg is `something.conf`
if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then
	set -- redis-server "$@"
fi

# allow the container to be started with `--user`
if [ "$1" = 'redis-server' -a "$(id -u)" = '0' ]; then
	find . \! -user redis -exec chown redis '{}' +
	exec gosu redis "$0" "$@"
fi

exec "$@"
root@10e778388e68:/data#

其中第一个 if 作知识补充整理:

if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then
	set -- redis-server "$@"
fi

 第一个判断  ${1#-} ,对带有 - 的前缀进行删掉第一个,如果是 -- 就删除只剩下一个 - :

把脚本拿出来进行测试改造:

[root@test 15:05:03/data/recycle]# cat sh.sh 
t=${1#-}
echo $t

if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then
	set -- redis-server "$@"
fi
[root@test 15:05:23/data/recycle]#
[root@test 15:12:11/data/recycle]# sh -x sh.sh 78
+ t=78
+ echo 78
78

+ '[' 78 '!=' 78 ']'
+ '[' 78 '!=' 78 ']'
[root@test 15:12:15/data/recycle]# sh -x sh.sh -78
+ t=78
+ echo 78
78

+ '[' 78 '!=' -78 ']'
+ set -- redis-server -78
[root@test 15:12:21/data/recycle]# sh -x sh.sh --78
+ t=-78
+ echo -78
-78

+ '[' -78 '!=' --78 ']'
+ set -- redis-server --78
[root@test 15:12:25/data/recycle]# 

第二个判断  ${1%.conf},对带有 .conf 的后缀进行删掉:

把脚本拿出来进行测试改造

s=${1%.conf}
echo $s

if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then
        set -- redis-server "$@"
fi
[root@test 15:12:25/data/recycle]# sh -x sh.sh 78.conf
+ s=78
+ echo 78
78
+ '[' 78.conf '!=' 78.conf ']'
+ '[' 78 '!=' 78.conf ']'
+ set -- redis-server 78.conf
[root@test 15:15:25/data/recycle]# sh -x sh.sh 78
+ s=78
+ echo 78
78
+ '[' 78 '!=' 78 ']'
+ '[' 78 '!=' 78 ']'
[root@test 15:15:27/data/recycle]# 

其中两个命令知识补充:

find . \! -user redis -exec chown redis '{}' +
exec gosu redis "$0" "$@"

find  \!  取反,这里表示不是 redis 用户的文件或目录查找出来, + 跟 \; 做结尾是一样的意思。

gosu命令是docker作为安全的最好要求,在容器中用gosu工具替换sudo命令去执行,而且能保证ps中的id进程为1。

这篇文章有详解

docker与gosu_程序员欣宸的博客-CSDN博客_docker gosu

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值