[英]How to change a command line argument in Bash?
Is there a way to change the command line arguments in a Bash script?有没有办法在 Bash 脚本中更改命令行参数? For example, a Bash script is invoked like this:
例如,像这样调用 Bash 脚本:
./foo arg1 arg2
Is there a way to change the value of arg1 within the script?有没有办法在脚本中更改 arg1 的值? Something like:
类似的东西:
$1="chintz"
You have to reset all arguments.您必须重置所有参数。 To change eg
$3
:改变例如
$3
:
$ set -- "${@:1:2}" "new" "${@:4}"
Basically you set all arguments to their current values, except for the one(s) that you want to change.基本上,您将所有参数设置为其当前值,但要更改的参数除外。
set --
is also specified by POSIX 7 . set --
也由 POSIX 7指定。
The "${@:1:2}"
notation is expanded to the two (hence the 2
in the notation) positional arguments starting from offset 1
(ie $1
). "${@:1:2}"
表示法扩展为从偏移量1
(即$1
)开始的两个(因此是表示法中的2
)位置参数。 It is a shorthand for "$1" "$2"
in this case, but it is much more useful when you want to replace eg "${17}"
.在这种情况下,它是
"$1" "$2"
的简写,但是当您想要替换例如"${17}"
时它更有用。
优化易读性和可维护性,您最好将$1
和$2
分配给更有意义的变量(我不知道, input_filename = $1
和output_filename = $2
或其他),然后覆盖这些变量之一( input_filename = 'chintz'
) ,保持脚本的输入不变,以防其他地方需要它。
I know this is an old one but I found the answer by thkala very helpful, so I have used the idea and expanded on it slightly to enable me to add defaults for any argument which has not been defined - for example:我知道这是一个旧的,但我发现thkala的答案非常有帮助,所以我使用了这个想法并稍微扩展了它,使我能够为任何尚未定义的参数添加默认值 - 例如:
# set defaults for the passed arguments (if any) if not defined.
#
arg1=${1:-"default-for-arg-1"}
arg2=${2:-"default-for-arg-2"}
set -- "${arg1}" "${arg2}"
unset arg1 arg2
I hope this is of use to someone else.我希望这对其他人有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.