Command line arguments

You're probably already aware of providing command line arguments when working with standard command lines, such as:

ls -la /var/www/

which is supplying two command line arguments (the first being) -la along with the path to use (as the second argument) /var/www/ which lists the contents of /var/www/ in long format with all files and directories.

 

Similarly, we can use the same approach to provide arguments into our shell scripts, with $1 being used within the shell script to represent the first argument and $2 used to represent the second argument and so on. These are automatically set by the system when we run our script so all we need to do is refer to them.

 

#!/bin/bash

echo "The first argument is: " $1

echo "The second argument is: " $2

 

The arguments are passed into the script on the actual command line, by specifying the script name followed by the arguments separated by a space:

 

./arguments.sh Hello, World!
The first argument is: Hello,
The second argument is: World!