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

时间:2021-08-09 16:49:58

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

4 个解决方案

#1


61  

you use $1, $2 in your script eg

你在脚本中使用$1,$2

date1="$1"
date2="$2"
sed "s/$date1/$date2/g" wlacd_stat.xml >temp.xml ;mv temp.xml wlacd_stat.xml #Semicolon can also replaced with a newline

#2


9  

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 "$@".

此表与“$@”中的a相同。

#3


7  

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

#4


6  

$0 $1 $2

$ 0 $ 1 $ 2

And so on will contain the script name, then the first and the second line argument.

然后将包含脚本名,然后是第一个和第二个行参数。

#1


61  

you use $1, $2 in your script eg

你在脚本中使用$1,$2

date1="$1"
date2="$2"
sed "s/$date1/$date2/g" wlacd_stat.xml >temp.xml ;mv temp.xml wlacd_stat.xml #Semicolon can also replaced with a newline

#2


9  

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 "$@".

此表与“$@”中的a相同。

#3


7  

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

#4


6  

$0 $1 $2

$ 0 $ 1 $ 2

And so on will contain the script name, then the first and the second line argument.

然后将包含脚本名,然后是第一个和第二个行参数。