如何在 Bash 中更改命令行参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4827690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change a command line argument in Bash?
提问by Sriram
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:
有没有办法在 Bash 脚本中更改命令行参数。例如,Bash 脚本的调用方式如下:
./foo arg1 arg2
Is there a way to change the value of arg1 within the script? Say, something like
有没有办法在脚本中更改 arg1 的值?说,像
="chintz"
回答by thkala
You have to reset all arguments. To change e.g. $3
:
您必须重置所有参数。改变例如$3
:
$ set -- "${@:1:2}" "new" "${@:4}"
Basically you setallarguments 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}"
notationis 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}"
.
该"${@:1:2}"
表示法扩展为2
从偏移量1
(即$1
)开始的两个(因此在表示法中)位置参数。"$1" "$2"
在这种情况下,它是一种简写,但是当您想要替换 eg 时它更有用"${17}"
。
回答by Johnsyweb
Optimising for legibility and maintainability, you may be better off assigning $1
and $2
to more meaningful variables (I don't know, input_filename = $1
and output_filename = $2
or something) and then overwriting one of those variables (input_filename = 'chintz'
), leaving the input to the script unchanged, in case it is needed elsewhere.
优化可读性和可维护性,你可能会更好分配$1
和$2
更有意义的变量(我不知道,input_filename = $1
和output_filename = $2
什么的),然后重写这些变量(input_filename = 'chintz'
),使输入到脚本不变的情况下,它是其他地方需要。