简体   繁体   English

如何将参数传递给 Bash 脚本?

[英]How to pass parameters to a Bash script?

I have a bash script as below, and I want it to read two dates as parameters, for example: myshell date1 date2 .我有一个如下的 bash 脚本,我希望它读取两个日期作为参数,例如: myshell date1 date2 How do I assign parameters to variables date1 and date2 ?如何将参数分配给变量date1date2

sed "s/$date1/$date2/g" wlacd_stat.xml >tmp.xml
mv tmp.xml wlacd_stat.xml

You use $1 , $2 in your script.您在脚本中使用$1$2 Eg:例如:

date1="$1"
date2="$2"
sed "s/$date1/$date2/g" wlacd_stat.xml >temp.xml
mv temp.xml wlacd_stat.xml

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 "$@"相同。

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 $1
    shift
done
$0
$1
$2

And so on will contain the script name, then the first and the second line argument.依此类推将包含脚本名称,然后是第一行和第二行参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM