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
nameandagevariables using the syntaxvariable_name=value. For example,name="John"assigns the string "John" to thenamevariable, andage=30assigns the number 30 to theagevariable.Accessing Variables: We use the
echocommand to display the values of thenameandagevariables. By using the$prefix ($name,$age), we access the values stored in those variables.Modifying Variables: We modify the values of the
nameandagevariables. We assign a new value toname("Jane") and updateageby 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 thedatecommand with the+%Y-%m-%dformat specifier to get the current date and store it in thecurrent_datevariable.
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