ddz*_*wmm 17 shell bash shell-script arguments
至于./script.sh arg1 [arg2 arg3 ...], 命令行参数arg1, arg2, ... 可以通过$1, $2, ... 获取,但参数数量不固定。
在 shell 脚本中,我想将参数从开始传递arg2给程序,
#/bin/bash
...
/path/to/a/program [I want to pass arg2 arg3 ... to the program]
...
Run Code Online (Sandbox Code Playgroud)
因为可能有一个或多个参数,我该怎么做?
Tho*_*key 19
通常的方法是保存arg1 ( "$1")的副本并将参数移动一个,因此您可以将整个列表引用为"$@":
#!/bin/sh
arg1="$1"
shift 1
/path/to/a/program "$@"
Run Code Online (Sandbox Code Playgroud)
bash 当然有一些数组支持,但对于所提出的问题不需要它。
如果arg1是可选的,你会像这样检查它:
if [ $# != 0 ]
then
arg1="$1"
shift 1
fi
Run Code Online (Sandbox Code Playgroud)
hee*_*ayl 10
您可以使用参数扩展对位置参数进行切片。语法是:
${parameter:offset:length}
Run Code Online (Sandbox Code Playgroud)
如果length省略,则视为直到最后一个值。
当您要从第二个参数传递到最后一个参数时,您需要:
${@:2}
Run Code Online (Sandbox Code Playgroud)
例子:
$ foo() { echo "${@:2}" ;}
$ foo bar spam egg
spam egg
Run Code Online (Sandbox Code Playgroud)