Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to a Bash script?

Tags:

linux

bash

shell

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 
like image 859
chun Avatar asked Apr 15 '10 13:04

chun


People also ask

How in bash parameters are passed to a script?

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.

How do you pass a parameter to a shell script?

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.

Can you pass variables in shell 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.

How do I get command line arguments in bash?

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.


2 Answers

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 
like image 188
ghostdog74 Avatar answered Sep 22 '22 14:09

ghostdog74


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

like image 28
Dennis Williamson Avatar answered Sep 23 '22 14:09

Dennis Williamson