Mastering Shell Script Variables and User Input

Last updated at: September 08, 2024
Written by: Abdul

Understanding Variables in Shell Scripting

Variables are fundamental building blocks in shell scripting. They allow you to store and manipulate data within your scripts. Let's explore how to work with variables effectively in Bash scripting.

Declaring and Using Variables

In Bash, you can declare variables simply by assigning a value to a name. Here's the basic syntax:

variable_name=value

Important points to remember:

Example:

#!/bin/bash
my_name="John Doe"
age=30
echo "My name is $my_name and I am $age years old."

Working with Environment Variables

Environment variables are set by the shell and are available to all processes. Common environment variables include:

Example usage:

echo "My home directory is $HOME"
echo "My username is $USER"

Command Substitution in Bash

Command substitution allows you to use the output of a command as a value. There are two syntaxes:

result=$(command)
result=`command`  # Older syntax, less preferred

Example:

current_date=$(date +"%Y-%m-%d")
echo "Today's date is $current_date"

Reading User Input

The 'read' command is used to accept user input in Bash scripts. Here's how to use it:

echo "What's your name?"
read user_name
echo "Hello, $user_name!"

For silent input (e.g., passwords), use the -s option:

echo "Enter your password:"
read -s password
echo "Password received!"

Practical Example: User Information Script

Let's combine what we've learned into a practical script:

#!/bin/bash

# Get current user and date
current_user=$(whoami)
current_date=$(date +"%Y-%m-%d")

# Greet user and ask for information
echo "Hello $current_user! Today is $current_date."
echo "What's your favorite programming language?"
read fav_language

# Display information
echo "Great choice! Here's a summary:"
echo "User: $current_user"
echo "Date: $current_date"
echo "Favorite Language: $fav_language"
echo "Your home directory is: $HOME"

Conclusion

Understanding variables and user input is crucial for creating dynamic and interactive shell scripts. Practice using these concepts in your scripts to become more proficient in Bash scripting.

In our next article, we'll explore control structures in shell scripts, including if-else statements and loops. Stay tuned!