Bash Command Line Arguments
Bash Command Line Arguments are used to provide input to a bash shell script while executing the script.
In bash shell programming you can provide maximum of nine arguments to a shell script. Inside the shell script you can access the arguments as bash variables $1 , $2 , $3 … corresponding to first argument, second argument, third argument etc., respectively. For multiple digit arguments use curly braces as ${21} for 21st argument. But it is recommended that you limit your command line arguments to nine for maintaining compatibility to other shells and avoiding confusion.
Example 1
In this example we will read four arguments from command line, and use them in our script.
Bash Script
#!/bin/bash
echo "Hello $1 !"
echo "We like your place, $2."
echo "Thank you for showing interest to learn $3 : $4."
Output
arjun@arjun-VPCEH26EN:~/ws$ ./bash-command-line-arguments Arjun India Bash-Tutorial Command-Line-Arguments
Hello Arjun !
We like your place, India.
Thank you for showing interest to learn Bash-Tutorial : Command-Line-Arguments.
Note : If you are wondering what $0 would be, it is the shell script name you provide.
Example 2
Following is a Bash shell script to print total number of command line arguments passed to shell script.
Bash Script
#!/bin/bash
echo "$# arguments have been passed to this script, $0"
Output
arjun@arjun-VPCEH26EN:~/ws$ ./bash-command-line-arguments-2 Arjun India Bash-Tutorial Command-Line-Arguments as as s s s s s s s s s s s
17 arguments have been passed to this script, ./bash-command-line-arguments-2
Example 3
In the following example, we will write a bash shell script that uses more than nine arguments.
Curly braces are used like ${nn} , to access higher arguments (>9)
Bash Script
#!/bin/bash
echo "13th argument is ${13}"
Output
arjun@arjun-VPCEH26EN:~/ws$ ./bash-command-line-arguments-3 Bash-Tutorial Command-Line-Arguments a b c d e f g h i j k 5 27 9
13th argument is k
Conclusion
In this Bash Tutorial – Bash Command Line Arguments, we have learnt to read and use command line arguments inside bash shell scripts.