Linux and Networking

Linux and Networking

4.8. Arguments passed to a shell script.

Arguments are the parameters that we pass to a command to parameterize it. For example, when I type ps -ef, the “-ef” are the parameters that I pass to ps to do what I want. Also when I execute mv fichero.txt fichero2.txt, I pass two parameters to mv which are the name of the file to be renamed and the name we want to give it.

 

Within a script we can reference the arguments passed to it using the following variables:

 

$0 script name

$1 first argument

$2 second argument

And so on…

$# number of arguments passed

$* all arguments passed

To see how parameters work, let’s look at a program that checks if at least one parameter has been passed:

 

As you can see at the beginning of the script, I check with [ -z «$1» ] that at least the first parameter exists and if not, it shows the messages you see and exits with the exit command. That way it ends and the script does not continue executing.

 

The previous script can be used to create a somewhat more complex script like the following:

As you can see, I have reused the previous script to make a more complete one. This script establishes source and destination directories for the backup and a file (FICH) where the backup will be performed, which has the name backup- and the date it was performed.

 

Copy and run the above code. Check that it works and modify the code to change the name of the file and store the backups in another directory.

 

The Demeter Project