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
Positional Parameters. Arguments passed to a script are processed in the same order in which they're sent. The indexing of the arguments starts at one, and the first argument can be accessed inside the script using $1. Similarly, the second argument can be accessed using $2, and so on.
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
In a shell script, you can pass variables as arguments by entering arguments after the script name, for example ./script.sh arg1 arg2 . The shell automatically assigns each argument name to a variable. Arguments are set of characters between spaces added after the script.
You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.
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
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 "$@"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With