How to pass parameters to a Bash script?

LinuxBashShell

Linux Problem Overview


I have a bash script as below, and I want it to read two dates as parameters, for example: myshell date1 date2. How do I assign parameters to variables date1 and date2?

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

Linux Solutions


Solution 1 - Linux

You use $1, $2 in your script. E.g:

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

Solution 2 - Linux

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

Solution 3 - Linux

Bash arguments are named after their position.

Moreover, if you need to handle one argument after the other, you can shift them and always use $1:

while [ $# -gt 0 ]
do
    echo $1
    shift
done

Solution 4 - Linux

$0
$1
$2

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchunView Question on Stackoverflow
Solution 1 - Linuxghostdog74View Answer on Stackoverflow
Solution 2 - LinuxDennis WilliamsonView Answer on Stackoverflow
Solution 3 - LinuxmouvicielView Answer on Stackoverflow
Solution 4 - LinuxSimone MargaritelliView Answer on Stackoverflow