在看网上比较专业的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.

给个简单的示例看下:

1#!/bin/bash
2echo ${@:2}
3variable=${@:3}
4echo $variable
5
6# Example run:
7./ex.bash 1 2 3 4 5
82 3 4 5
93 4 5

通过上面的简单脚本示例,可以看出其对应的输出就是对$@的切片,这里可以看到除了${@:2},还可以使用了${@:3}

二、Dockerfile使用中的示例

Dockerfile文件内容如下:

1FROM node:7-alpine
2
3WORKDIR /app
4ADD . /app
5RUN npm install
6
7ENTRYPOINT ["./entrypoint.sh"]
8CMD ["start"]

对应的entrypoint.sh脚本内容如下:

 1#!/usr/bin/env sh
 2# $0 is a script name,
 3# $1, $2, $3 etc are passed arguments
 4# $1 is our command
 5CMD=$1
 6
 7case "$CMD" in
 8  "dev" )
 9    npm install
10    export NODE_ENV=development
11    exec npm run dev
12    ;;
13
14  "start" )
15    # we can modify files here, using ENV variables passed in
16    # "docker create" command. It can't be done during build process.
17    echo "db: $DATABASE_ADDRESS" >> /app/config.yml
18    export NODE_ENV=production
19    exec npm start
20    ;;
21
22   * )
23    # Run custom command. Thanks to this line we can still use
24    # "docker run our_image /bin/bash" and it will work
25    exec $CMD ${@:2}
26    ;;
27esac

可以看到这里的用法就是将后面的参数传进来执行。