Working with Arguments

Making a script interactive is a nice solution for getting user input. It has a disadvantage, though: it requires a user to provide input to your script. This is not ideal, because many scripts run automatically. These scripts, however, also start because of some specific parameters. The way to handle the parameters is by running them as an argument on start-up. For example, you would run the hello script from the previous section as ./hello hi to let it output the text hi.

To work with arguments that are provided when activating the script, you have to refer to them in the script. You can refer to the first argument by using $1, the second argument by using $2, and so on, up to $9. ($10 would be interpreted as $1, followed by 0.) You can refer to the name of the script by using $0. In Listing 27-7 you see a simple example of a script that can work with arguments.

Listing 27-7. Working with Arguments

# Script that allows you to greet someone

echo "Hello, $1, how are you today"

Let's imagine you activate this script by entering ./hello, linda on the command line. This means when calling the script, $1 is filled with the value linda. When called in the actual code line, the script will therefore echo "Hello, linda, how are you today" on the screen of the user. When working with arguments, you must be aware that every word you enter is interpreted as an argument by itself. This shows when you execute the script in the previous example by entering ./hello, mister president. As the result, only the text "Hello, mister, how are you today" displays. This is because your script doesn't have any definition for $2.

Want to make sure that cases like this are handled correctly? In that case, you should use $*. The construction $* handles an unknown number of arguments that is entered. So to handle any number of arguments, without knowing beforehand how many arguments are going to be used, tune the script from Listing 27-7 as shown in Listing 27-8.

Listing 27-8. Handling an Unknown Number of Arguments

# Script that allows you to greet one or more persons

# Usage: ./hello [name1] [name2] ... [namen] echo "Hello, $1, how are you today"

Was this article helpful?

0 0

Post a comment