Passing Arguments to Shell Scripts
Accessing Script Arguments
In shell scripting, you can pass arguments to a script when you run it. These arguments are stored in special variables that you can access within the script.
The first argument is stored in the $1
variable, the second argument is stored in the $2
variable, and so on. The special variable $0
contains the name of the script itself.
Here's an example script that demonstrates how to access script arguments:
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
To run this script with arguments, you would use the following command:
./my_script.sh "Hello" "World"
This would output:
Script name: ./my_script.sh
First argument: Hello
Second argument: World
Handling Optional Arguments
Sometimes, you may want to make certain arguments optional in your script. You can use conditional statements to check if the arguments are provided and take appropriate actions.
Here's an example script that demonstrates how to handle optional arguments:
#!/bin/bash
if [ -z "$1" ]; then
echo "No name provided. Using 'Guest' as the default."
name="Guest"
else
name="$1"
fi
echo "Hello, $name!"
In this script, if the first argument is not provided, the script will use the default value of "Guest". Otherwise, it will use the provided argument as the name.
Validating Arguments
It's important to validate the arguments passed to your script to ensure that they meet the expected criteria. You can use various shell commands and conditional statements to perform argument validation.
For example, you can check if a provided argument is a valid file or directory, or if it matches a specific pattern.
#!/bin/bash
if [ -f "$1" ]; then
echo "Processing file: $1"
else
echo "Error: $1 is not a valid file."
exit 1
fi
This script checks if the first argument is a valid file. If it is, the script proceeds with processing the file. If not, it displays an error message and exits with a non-zero status code to indicate an error.
Understanding how to pass, access, and validate arguments is crucial for creating more robust and flexible shell scripts.