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 and age variables using the syntax variable_name=value. For example, name="John" assigns the string "John" to the name variable, and age=30 assigns the number 30 to the age variable.

  • Accessing Variables: We use the echo command to display the values of the name and age variables. By using the $ prefix ($name, $age), we access the values stored in those variables.

  • Modifying Variables: We modify the values of the name and age variables. We assign a new value to name ("Jane") and update age 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 the date command with the +%Y-%m-%d format specifier to get the current date and store it in the current_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