如何在Bash中更改命令行参数? [英] How to change a command line argument in Bash?
问题描述
有没有一种方法可以更改Bash脚本中的命令行参数.例如,以下列方式调用Bash脚本:
Is there a way to change the command line arguments in a Bash script. Say for example, a Bash script is invoked the following way:
./foo arg1 arg2
是否可以在脚本中更改arg1的值?说,像
Is there a way to change the value of arg1 within the script? Say, something like
$1="chintz"
推荐答案
您必须重置所有参数.改变例如$3
:
You have to reset all arguments. To change e.g. $3
:
$ set -- "${@:1:2}" "new" "${@:4}"
基本上,您设置 所有参数设为当前值,但您要更改的参数除外. POSIX 7还 指定了set --
.
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.
"${@:1:2}"
表示法是从偏移量1
(即$1
)开始扩展到两个位置参数(因此用符号2
表示).在这种情况下,它是"$1" "$2"
的简写,但是当您要替换例如时,它会更有用. "${17}"
.
The "${@:1:2}"
notation is expanded to the two (hence the 2
in the notation) positional arguments starting from offset 1
(i.e. $1
). It is a shorthand for "$1" "$2"
in this case, but it is much more useful when you want to replace e.g. "${17}"
.
这篇关于如何在Bash中更改命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!