In some Bash scripts, there is an option to pass arguments to the script when you are executing it. This allows the user to specify more information in the same command used to run the script.
This is yet another way for us to accept input in a Bash script, and make our script more interactive with the user executing it. Command line arguments are specified as extra bits of information (or flags/options) that are passed to the script.
In this tutorial, you will learn how to accept command line arguments in a Bash script on a Linux system. Follow along with our example below to see how it works.
In this tutorial you will learn:
- How to detect number of command line arguments
- How to use command line arguments in a Bash script
|Category||Requirements, Conventions or Software Version Used|
|System||Any Linux distro|
|Software||Bash shell (installed by default)|
|Other||Privileged access to your Linux system as root or via the
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of
$ – requires given linux commands to be executed as a regular non-privileged user
Bash Scripting: Command line arguments example
Let’s look at a basic example of how we can use command line arguments with our Bash script. The following script will accept two command line arguments – a file name and a bit of text to put inside of the file.
#!/bin/bash if [ $# -ne 2 ]; then echo "please specify 2 command line arguments" exit 1 fi touch $1 echo $2 > $1
Here is how we would pass our two arguments to the script:
$ ./test.sh hello_world.txt "Hello World!"
Note that we wrapped our second command line argument in quotes since it contains a space. The result from executing the above command is a
hello_world.txt file gets generated and contains the text we specified:
$ cat hello_world.txt Hello World!
if statement at the beginning of the script uses the
$# variable to test the number of arguments we have passed to the script. If it is any value other than 2, the script will issue an error and exit.
$ ./test.sh please specify 2 command line arguments
After passing that bit of error detection, the script will use the
touch command on the first command line argument we passed. Then it will use the
echo command to put our second command line argument into the file the script created. It uses our passed arguments through the variables
$2. The values of our arguments are placed into those variables automatically.
In this tutorial, we saw how to pass command line arguments to a Bash script on Linux. Using the numbered variables like
$2, etc, we can use the data passed to the script. This is one of the few ways to pass data to a Bash script and make it interactive, but it is very effective and simple to code, as you learned here.