如何将参数传递给 Linux Bash 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2645636/
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 pass parameters to a Linux Bash script?
提问by chun
I have a Linux bash script 'myshell'. I want it to read two dates as parameters, for example: myshell date1 date2
. I am a Java programmer, but don't know how to write a script to get this done.
我有一个 Linux bash 脚本“myshell”。我希望它读取两个日期作为参数,例如:myshell date1 date2
. 我是一名 Java 程序员,但不知道如何编写脚本来完成这项工作。
The rest of the script is like this:
脚本的其余部分是这样的:
sed "s/$date1/$date2/g" wlacd_stat.xml >tmp.xml
mv tmp.xml wlacd_stat.xml
采纳答案by ghostdog74
you use $1
, $2
in your script eg
你在你的脚本中使用$1
,$2
例如
date1=""
date2=""
sed "s/$date1/$date2/g" wlacd_stat.xml >temp.xml ;mv temp.xml wlacd_stat.xml #Semicolon can also replaced with a newline
回答by Simone Margaritelli
$0 $1 $2
$0 $1 $2
And so on will contain the script name, then the first and the second line argument.
依此类推将包含脚本名称,然后是第一行和第二行参数。
回答by mouviciel
Bash arguments are named after their position.
Bash 参数以其位置命名。
Moreover, if you need to handle one argument after the other, you can shift them and always use $1
:
此外,如果您需要一个接一个地处理一个参数,您可以移动它们并始终使用$1
:
while [ $# -gt 0 ]
do
echo
shift
done
回答by Paused until further notice.
To iterate over the parameters, you can use this shorthand:
要迭代参数,您可以使用以下简写:
#!/bin/bash
for a
do
echo $a
done
This form is the same as for a in "$@"
.
这种形式与for a in "$@"
.