Variables in Shell Scripting
This tutorial provides a detailed explanation of using variables in shell scripts, including their declaration, usage, and different types.
1. Introduction to Variables
Variables in shell scripting are used to store and manipulate data. They can hold different types of values, such as strings, numbers, and the results of commands.
2. Declaring and Assigning Variables
To declare and assign a variable, use the following syntax:
variable_name=value
There should be no spaces around the =
sign. Example:
#!/bin/bash
greeting="Hello, World!"
echo $greeting
In this example, the variable greeting
is assigned the value "Hello, World!"
, and then it is printed using the echo
command.
3. Accessing Variable Values
To access the value of a variable, prefix its name with a dollar sign ($
):
#!/bin/bash
name="Alice"
echo "Hello, $name"
This script will output Hello, Alice
.
4. Using Command Substitution
Command substitution allows you to assign the output of a command to a variable. Use the $(command)
syntax:
#!/bin/bash
current_date=$(date)
echo "Today is $current_date"
This script assigns the current date and time to the current_date
variable and then prints it.
5. Quoting Variable Values
When working with variables that contain spaces or special characters, use double quotes to preserve their values:
#!/bin/bash
path="/home/user/my folder"
echo "The path is $path"
This ensures that the entire value of path
is treated as a single string.
6. Read-only Variables
You can declare a variable as read-only to prevent its value from being changed:
#!/bin/bash
name="Alice"
readonly name
name="Bob" # This will cause an error
echo $name
Attempting to change a read-only variable will result in an error.
7. Unsetting Variables
To unset (delete) a variable, use the unset
command:
#!/bin/bash
name="Alice"
unset name
echo $name
After unsetting, the variable name
no longer holds a value.
8. Special Variables
Shell scripting provides several special variables:
$0
: The name of the script$1, $2, ...
: The first, second, etc., arguments to the script$#
: The number of arguments passed to the script$@
: All the arguments passed to the script$?
: The exit status of the last executed command$$
: The process ID of the current shell$!
: The process ID of the last background command
Example:
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Number of arguments: $#"
If you run this script with arguments ./script.sh arg1 arg2
, it will output:
Script name: ./script.sh
First argument: arg1
Number of arguments: 2
9. Conclusion
In this tutorial, you learned how to use variables in shell scripts, including declaring and assigning variables, accessing their values, using command substitution, quoting variable values, declaring read-only variables, unsetting variables, and understanding special variables. Mastering these concepts is essential for writing effective shell scripts.