In shell scripting, variables are fundamental constructs that store data for use in scripts. They allow for dynamic content manipulation and can simplify the tasks performed by scripts. This article provides three diverse examples of variables in shell scripting, showcasing different contexts and use cases.
In this example, we will create a simple script that prompts the user for their name and stores it in a variable. This is useful for personalizing outputs in scripts.
#!/bin/bash
# Prompt the user for their name
read -p "Enter your name: " USER_NAME
# Greet the user using the variable
echo "Hello, $USER_NAME! Welcome to our script."
This script uses the read
command to take input from the user and stores it in the USER_NAME
variable. The variable is then used in the echo
command to display a personalized message.
chmod +x script.sh
before running it.Environment variables can be set and accessed within shell scripts. This example demonstrates how to use an environment variable to define a directory path that can be reused throughout the script.
#!/bin/bash
# Set an environment variable for the directory
export PROJECT_DIR="/home/user/projects"
# Use the variable to navigate to the directory and list files
cd $PROJECT_DIR
ls -l
In this script, we set an environment variable named PROJECT_DIR
to a specific directory path. This variable is then used to change the current directory with cd
and list the files within it.
unset VARIABLE_NAME
if needed.Shell scripting allows for arithmetic operations directly using variables. This example illustrates how to declare numeric variables, perform calculations, and display results.
#!/bin/bash
# Declare two numeric variables
NUM1=10
NUM2=5
# Perform arithmetic operations
SUM=$((NUM1 + NUM2))
DIFF=$((NUM1 - NUM2))
PRODUCT=$((NUM1 * NUM2))
QUOTIENT=$((NUM1 / NUM2))
# Display the results
echo "Sum: $SUM"
echo "Difference: $DIFF"
echo "Product: $PRODUCT"
echo "Quotient: $QUOTIENT"
This script defines two numeric variables, NUM1
and NUM2
, and calculates their sum, difference, product, and quotient using the $(( ))
syntax. The results are then printed using the echo
command.
bc
for handling floating-point arithmetic if necessary.By understanding and utilizing these examples of variables in shell scripting, you can enhance your scripting capabilities and introduce more dynamic functionality into your scripts.