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"
.
A shell variable is a named storage location for data. Variables can be used to store any type of data, such as strings, numbers, or dates.
To create a shell variable, you simply assign a value to it using the equals sign (=
). For example, to create a variable called name
and assign it the value "John Doe", you would use the following command:
name="John Doe"
Once you have created a variable, you can use it in your shell script by referencing its name. For example, to print the value of the name
variable to the console, you would use the following command:
echo $name
Here are some examples of how to use variables in shell scripts:
# Create a variable to store the user's name
name=$USER
# Print the user's name to the console
echo "Hello, $name!"
# Create a variable to store the current date and time
now=$(date)
# Print the current date and time to the console
echo "The current date and time is: $now"
# Create a variable to store the name of a file
file="myfile.txt"
# Check if the file exists
if [ -f $file ]; then
echo "The file $file exists."
else
echo "The file $file does not exist."
fi
Enroll Now