Arduino (1) Brainf**k (1) Bugs (3) C (1) HTML (1) Install (3) Linux (27) Maths (1) Python (12) Raspberry Pi (4)

Monday, 29 May 2017

Command line parameters in shell scripts

Command line parameters are a way to pass information into a program or script in order for it to do what you want it to. Some examples of command line parameters:

ls -l
cat textfile
The command line parameters here are the "-l" and "textfile"

How are command line parameters accessed within a shell script?
They are stored in these variables:
"$0":This holds the name of the command.
"$1":This holds the first parameter.
"$2":This holds the second parameter.
"$3":This holds the third parameter and the pattern repeats.
"$#":This holds the number of parameters that have been passed.
"$@":This holds all of the parameters

Lets make a simple script call it
echo "Name of script:$0"
echo "First parameter:$1"
echo "Second parameter:$2"
echo "Number of parameters:$#"
echo "All parameters:$@"
When we run the script you should get the following output
sh hello world
Name of
First parameter:hello
Second parameter:world
Number of parameters:2
All parameters:hello world