To input arguments into a Bash script, like any normal command line program, there are special variables set aside for this
The arguments are stored in variables with a number in the order of the argument starting at 1
- First Argument: $1
- Second Argument: $2
- Third Argument: $3
- command: ./script.bash alpha beta gamma
- Variables: $1=='alpha'; $2=='beta'; $3=='gamma'
The variable $0 is the script's name. The total number of arguments is stored in $#. The variables $@ and $* return all the arguments.
For more complicated examples, you might consider getopt: http://aplawrence.com/Unix/getopts.html
#!/bin/bash echo "the $1 eats a $2 every time there is a $3" echo "bye:-)"
- Command: ./script.bash dog bone moose
- the dog eats a bone every time there is a moose
Get user input:
After the mammoth previous section this one is much easier to get through.
Ask the User for InputIf we would like to ask the user for input then we use a command called read. This command takes the input and will save it into a variable.
read var1Let's look at a simple example:
- # Ask the user for their name
- echo Hello, who am I talking to?
- read varname
- echo It\'s nice to meet you $varname
- Line 4 - Print a message asking the user for input.
- Line 6 - Run the command read and save the users response into the variable varname
- Line 8 - echo another message just to verify the read command worked. Note: I had to put a backslash ( \ ) in front of the ' so that it was escaped.
- Hello, who am I talking to?
- It's nice to meet you Ryan
- Note: Ryan above is in italics just to show that it was something I typed in. On your terminal input will show up normally.
More with ReadYou are able to alter the behaviour of read with a variety of command line options. (See the man page for read to see all of them.) Two commonly used options however are -p which allows you to specify a prompt and -s which makes the input silent. This can make it easy to ask for a username and password combination like the example below:
- # Ask the user for login details
- read -p 'Username: ' uservar
- read -sp 'Password: ' passvar
- echo Thankyou $uservar we now have your login details
- On lines 4 and 5 above we include the prompt within quotes so we can have a space included with it. Otherwise the user input will start straight after the last character of the prompt which isn't ideal from a readability point of view.
- Username: ryan
- Thankyou ryan we now have your login details
More variablesSo far we have looked at a single word as input. We can do more than that however.
- # Demonstrate how read actually works
- echo What cars do you like?
- read car1 car2 car3
- echo Your first car was: $car1
- echo Your second car was: $car2
- echo Your third car was: $car3