在看网上比较专业的Dockerfile的启动脚本中(ENTRYPOINT对应的启动文件)中经常会看到${@:2}这样的写法。该变量的用法有点类似于python中数组的切片,这里显示的是所有传参中,从第二个参数开始到结尾的所有参数的集合,其就是对$@变量的切片。
一、$@释义
看下一段关于这个变量的英文描述:
It’s showing the contents of the special variable $@
, in Bash. It contains all the command line arguments, and this command is taking all the arguments from the second one on and storing them in a variable, variable
.
给个简单的示例看下:
#!/bin/bash
echo ${@:2}
variable=${@:3}
echo $variable
# Example run:
./ex.bash 1 2 3 4 5
2 3 4 5
3 4 5
通过上面的简单脚本示例,可以看出其对应的输出就是对$@的切片,这里可以看到除了${@:2}
,还可以使用了${@:3}
。
二、Dockerfile使用中的示例
Dockerfile文件内容如下:
FROM node:7-alpine
WORKDIR /app
ADD . /app
RUN npm install
ENTRYPOINT ["./entrypoint.sh"]
CMD ["start"]
对应的entrypoint.sh脚本内容如下:
#!/usr/bin/env sh
# $0 is a script name,
# $1, $2, $3 etc are passed arguments
# $1 is our command
CMD=$1
case "$CMD" in
"dev" )
npm install
export NODE_ENV=development
exec npm run dev
;;
"start" )
# we can modify files here, using ENV variables passed in
# "docker create" command. It can't be done during build process.
echo "db: $DATABASE_ADDRESS" >> /app/config.yml
export NODE_ENV=production
exec npm start
;;
* )
# Run custom command. Thanks to this line we can still use
# "docker run our_image /bin/bash" and it will work
exec $CMD ${@:2}
;;
esac
可以看到这里的用法就是将后面的参数传进来执行。