In shell scripting, variables are used to store and manipulate data. Shell scripts support several types of variables, including:
User-Defined Variables:
=
operator without spaces around it.my_variable="Hello, World!"
System Variables:
PATH
, HOME
, USER
, SHELL
, and PWD
.$
symbol followed by the variable name.echo "My home directory is $HOME"
Positional Parameters:
$0
represents the script's name, and $1
, $2
, etc., represent the first, second, and so on, arguments.echo "Script name: $0" echo "First argument: $1"
Special Variables:
$$
(current process ID), $?
(exit status of the last command), and $#
(number of arguments).echo "Process ID: $$"
Array Variables:
[ ]
.my_array=("apple" "banana" "cherry") echo "First fruit: ${my_array[0]}"
Read-Only Variables:
readonly
keyword. Once a variable is read-only, its value cannot be changed.readonly my_readonly_variable="This is read-only"
Environment Variables:
export
command.export MY_ENV_VAR="This is an environment variable"
Local Variables (in Functions):
my_function() {
local local_var="This is a local variable"
echo "$local_var"
}
To use the value of a variable, you typically enclose its name in double quotes to ensure that any spaces or special characters are handled correctly. For example: "$my_variable"
.