Variables are fundamental components of shell scripting that allow scripts to store, manipulate, and retrieve data dynamically. Unlike some programming languages, shell scripting in Linux does not enforce strict data types, making variables versatile and straightforward to use. Understanding how to declare, access, and use variables effectively is essential for writing flexible and powerful scripts that automate system tasks.
What are Variables?
A variable is a symbolic name assigned to a value or data. They enable scripts to hold data such as numbers, text strings, or the output of commands. Variables can be local to a script, global within a shell session, or environment variables inherited by subprocesses.
Defining and Accessing Variables
Variables are defined by assigning values without spaces around the = operator.
Example:
NAME="Alice"
AGE=30echo "Name is $NAME and age is $AGE"echo "This is ${NAME}'s file."Variable Naming Rules
Variable naming rules require that names begin with a letter (a–z or A–Z) or an underscore (_), and any characters that follow may include only letters, numbers, or underscores. Variable names are case-sensitive, meaning var, Var, and VAR are treated as different identifiers. To avoid errors and ensure compatibility, special characters, spaces, and names that start with numbers should not be used.
Valid examples:
USERNAME, var_name, COUNTER1, _tempInvalid examples:
1variable, var-name, user!nameTypes of Variables in Shell Scripting
Although shell variables are typeless strings, conventionally, various types exist:
1. Scalar Variables: Hold single values such as strings or integers.
2. Array Variables: Store multiple values as ordered lists.
Example:
fruits=("apple" "banana" "orange")
echo ${fruits[1]} # outputs "banana"3. Read-only Variables: Declared with readonly or declare -r keyword; cannot be modified or unset.
Example:
readonly PI=3.14154. Environment Variables: Exported variables available to child processes using export.
Example:
export PATH=/usr/bin:$PATHSpecial Variables
1. $0: Name of the script.
2. $1, $2, ...: Positional parameters or script arguments.
3. $#: Number of arguments.
4. $?: Exit status of last command.
5. $$: Process ID of the current shell.
6. $!: Process ID of the last background command.
Working with Variables
Below are the essential ways to work with variables in scripts. They enable dynamic and flexible program behavior.
1. Reading user input:
read USERNAME
echo "User entered: $USERNAME"2. Arithmetic operations: Use $(( )) for calculating expressions.
Example:
a=10
b=20
c=$((a + b))
echo $c # Outputs 303. String operations: Strings can be concatenated simply via juxtaposition:
greeting="Hello"
name="Alice"
message="$greeting, $name"
echo $message