Handling Shell Script Arguments
Shell scripts can accept arguments, which are values passed to the script when it is executed. These arguments can be used to make the script more flexible and adaptable to different use cases.
Accessing Script Arguments
Within the shell script, you can access the arguments using the special variables $1
, $2
, $3
, and so on. The $1
variable represents the first argument, $2
represents the second argument, and so on.
Here's an example script that demonstrates how to use arguments:
#!/bin/bash
echo "Hello, $1!"
echo "You are $2 years old."
To run this script and pass the name and age as arguments, you would use the following command:
./hello.sh LabEx 30
This would output:
Hello, LabEx!
You are 30 years old.
Handling Optional Arguments
Sometimes, you may want to make certain arguments optional. You can do this by checking if the argument is provided before using it. Here's an example:
#!/bin/bash
if [ -z "$1" ]; then
echo "Please provide a name as an argument."
else
echo "Hello, $1!"
fi
if [ -n "$2" ]; then
echo "You are $2 years old."
else
echo "Age not provided."
fi
In this script, the first if
statement checks if the first argument ($1
) is empty (-z "$1"
). If it is, the script prints a message asking the user to provide a name. The second if
statement checks if the second argument ($2
) is not empty (-n "$2"
). If it is provided, the script prints the age, otherwise, it prints a message saying the age was not provided.
Handling Multiple Arguments
You can also handle multiple arguments by using a loop. Here's an example:
#!/bin/bash
echo "The arguments are:"
for arg in "$@"; do
echo "- $arg"
done
In this script, the "$@"
variable represents all the arguments passed to the script. The for
loop iterates over each argument and prints it.
To run this script with multiple arguments, you would use the following command:
./list_args.sh apple banana cherry
This would output:
The arguments are:
- apple
- banana
- cherry
By understanding how to handle arguments in shell scripts, you can create more powerful and versatile scripts that can adapt to different use cases and requirements.