Variables
Here's an example of a shell script that demonstrates variable usage:
#!/bin/bash
# Variable assignment
name="John"
age=30
# Accessing variables
echo "Name: $name"
echo "Age: $age"
# Modifying variables
name="Jane"
age=$((age + 5))
echo "Modified Name: $name"
echo "Modified Age: $age"
# Command substitution
current_date=$(date +%Y-%m-%d)
echo "Current Date: $current_date"
In this script, we have the following variable-related operations:
Variable Assignment: We assign values to the
name
andage
variables using the syntaxvariable_name=value
. For example,name="John"
assigns the string "John" to thename
variable, andage=30
assigns the number 30 to theage
variable.Accessing Variables: We use the
echo
command to display the values of thename
andage
variables. By using the$
prefix ($name
,$age
), we access the values stored in those variables.Modifying Variables: We modify the values of the
name
andage
variables. We assign a new value toname
("Jane") and updateage
by adding 5 to its current value using arithmetic expansion ($((expression))
).Command Substitution: We use the
$(command)
syntax to perform command substitution. In this example, we use thedate
command with the+%Y-%m-%d
format specifier to get the current date and store it in thecurrent_date
variable.
When you run the script, it will display the initial values of name
and age
, then the modified values after the variable updates. Finally, it will print the current date obtained through command substitution.
Last updated