Shell Scripting Basics: First Step to Automation

Shell scripting is a powerful tool for automating tasks in Linux systems. In this basics edition, you'll learn Bash script syntax from variables and conditionals to loops, with practical examples throughout.

Table of Contents

  1. Your First Shell Script
  2. Variables and Input
  3. Conditionals
  4. Loops

1. Your First Shell Script

Basic Structure

First Script

#!/bin/bash
# This is a comment

echo "Hello, Shell Script!"
echo "Current date/time: $(date)"
echo "Username: $USER"

Creating and Running Scripts

Step 1: Create File

$ nano hello.sh

Enter the above code and save

Step 2: Add Execute Permission

$ chmod +x hello.sh

Step 3: Run Script

$ ./hello.sh
Hello, Shell Script!
Current date/time: Mon Jan 11 14:30:00 JST 2025
Username: user

About Shebang

#!/bin/bash is called a shebang and specifies the interpreter to execute this file.

  • #!/bin/bash - Use Bash
  • #!/bin/sh - Use POSIX shell
  • #!/usr/bin/env bash - Auto-detect from environment

2. Variables and Input

Variable Basics

Defining and Using Variables

#!/bin/bash

# Define variables (no spaces around =)
name="Linux User"
age=25
today=$(date +%Y-%m-%d)

# Use variables
echo "Name: $name"
echo "Age: ${age} years old"
echo "Today's date: $today"

Calculation Example

#!/bin/bash

num1=10
num2=3

# Numeric calculations
sum=$((num1 + num2))
diff=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))

echo "Addition: $num1 + $num2 = $sum"
echo "Subtraction: $num1 - $num2 = $diff"
echo "Multiplication: $num1 Γ— $num2 = $product"
echo "Division: $num1 Γ· $num2 = $quotient"

Special Variables

Variable Description Example
$0 Script name ./script.sh
$1, $2, ... Command line arguments 1st arg, 2nd arg
$# Number of arguments 3 for 3 arguments
$@ All arguments "arg1" "arg2" "arg3"
$? Exit status of last command 0 for success, non-0 for failure
$$ Current process ID 12345
$USER Current username user
$HOME Home directory /home/user
$PWD Current directory /home/user/scripts

User Input

Basic Input

#!/bin/bash

echo "Please enter your name:"
read name
echo "Hello, ${name}!"

Input with Prompt

#!/bin/bash

read -p "Enter your age: " age
read -s -p "Enter password: " password
echo
echo "Age: $age"
echo "Password entered silently"

Multiple Values at Once

#!/bin/bash

echo "Enter name and age (space-separated):"
read name age
echo "Name: $name, Age: $age"

3. Conditionals

if Statement

Basic if Statement

#!/bin/bash

read -p "Enter a number: " num

if [ $num -gt 0 ]; then
    echo "$num is positive"
elif [ $num -lt 0 ]; then
    echo "$num is negative"
else
    echo "$num is zero"
fi

File Existence Check

#!/bin/bash

filename="test.txt"

if [ -f "$filename" ]; then
    echo "$filename exists"
    echo "File size: $(wc -c < "$filename") bytes"
else
    echo "$filename does not exist"
    echo "Creating file..."
    touch "$filename"
fi

Conditional Operators

Numeric Comparison

OperatorMeaningExample
-eqEqual[ $a -eq $b ]
-neNot equal[ $a -ne $b ]
-gtGreater than[ $a -gt $b ]
-geGreater or equal[ $a -ge $b ]
-ltLess than[ $a -lt $b ]
-leLess or equal[ $a -le $b ]

String Comparison

OperatorMeaningExample
=Equal[ "$a" = "$b" ]
!=Not equal[ "$a" != "$b" ]
-zEmpty string[ -z "$str" ]
-nNot empty[ -n "$str" ]

File Tests

OperatorMeaningExample
-fRegular file[ -f file.txt ]
-dDirectory[ -d /home ]
-eExists[ -e path ]
-rReadable[ -r file ]
-wWritable[ -w file ]
-xExecutable[ -x script ]

case Statement

Menu Selection Example

#!/bin/bash

echo "Select an option:"
echo "1) List files"
echo "2) Show current time"
echo "3) Show system info"
echo "4) Exit"

read -p "Choice (1-4): " choice

case $choice in
    1)
        echo "=== File List ==="
        ls -la
        ;;
    2)
        echo "=== Current Time ==="
        date
        ;;
    3)
        echo "=== System Info ==="
        uname -a
        ;;
    4)
        echo "Exiting."
        exit 0
        ;;
    *)
        echo "Invalid choice."
        ;;
esac

4. Loops

for Loop

Basic for Loop

#!/bin/bash

# Numeric range
for i in {1..5}
do
    echo "Count: $i"
done

echo "---"

# File processing
for file in *.txt
do
    echo "Processing: $file"
    wc -l "$file"
done

Loop with Arrays

#!/bin/bash

# Define array
fruits=("apple" "banana" "orange" "grape")

echo "Fruit list:"
for fruit in "${fruits[@]}"
do
    echo "- $fruit"
done

C-style for Loop

#!/bin/bash

echo "Multiplication table (partial):"
for ((i=1; i<=5; i++))
do
    for ((j=1; j<=5; j++))
    do
        result=$((i * j))
        printf "%2d " $result
    done
    echo
done

while Loop

Basic while Loop

#!/bin/bash

count=1
while [ $count -le 5 ]
do
    echo "Loop iteration $count"
    count=$((count + 1))
done

Reading Files

#!/bin/bash

filename="data.txt"

if [ -f "$filename" ]; then
    while IFS= read -r line
    do
        echo "Read: $line"
    done < "$filename"
else
    echo "File $filename not found"
fi

until Loop

Repeat Until Condition is True

#!/bin/bash

count=1
until [ $count -gt 5 ]
do
    echo "Count: $count"
    count=$((count + 1))
done

Loop Control

  • break - Exit loop
  • continue - Skip to next iteration
#!/bin/bash

for i in {1..10}
do
    if [ $i -eq 3 ]; then
        echo "Skipping 3"
        continue
    fi

    if [ $i -eq 8 ]; then
        echo "Stopping at 8"
        break
    fi

    echo "Number: $i"
done

⚠️ Common Beginner Mistakes and Pitfalls

Detailed explanations of common problems beginners frequently encounter and how to avoid them.

🚫 Mistake 1: Spaces in Variable Assignment

❌ Error-causing Examples

name = "Taro"     # Space before/after =
age= 25          # Space after =
city ="Tokyo"     # Space before =

Results in "command not found" error.

βœ… Correct Usage

name="Taro"      # No spaces around =
age=25          # No spaces around =
city="Tokyo"     # No spaces around =

Variable assignment must have no spaces around =.

🚫 Mistake 2: Missing Braces in Variable Reference

❌ Unexpected Results

filename="test"
echo "$filenameback.txt"    # Empty
echo "$filename_backup"     # Empty

Variable name boundary unclear, not expanded properly.

βœ… Correct Usage

filename="test"
echo "${filename}back.txt"   # testback.txt
echo "${filename}_backup"    # test_backup

Use {} to clearly define variable name scope.

🚫 Mistake 3: Missing Spaces in if Statement Conditions

❌ Error-causing Examples

if [$num -gt 5]; then       # No space after [
if [ $num -gt 5]; then       # No space before ]
if [$num -gt 5 ]; then       # No space after [

Syntax errors occur.

βœ… Correct Usage

if [ $num -gt 5 ]; then     # Spaces inside [ ] required
if [[ $num -gt 5 ]]; then    # Same for [[ ]]
if (( $num > 5 )); then      # Arithmetic expression

Always include spaces inside [ ].

🚫 Mistake 4: Missing Quotes in String Comparison

❌ Dangerous Examples

if [ $name = John Doe ]; then    # Issues with spaces
if [ $empty_var = "" ]; then     # Error when empty

Errors occur when variable is empty or contains spaces.

βœ… Safe Usage

if [ "$name" = "John Doe" ]; then    # Quote both sides
if [ "$empty_var" = "" ]; then       # No error when empty
if [ -z "$var" ]; then               # Dedicated empty check option

Always quote variables for safety.

🚫 Mistake 5: Old Command Substitution Syntax

❌ Old Syntax (Not Recommended)

date=`date`                 # Backticks
files=`ls *.txt`            # Difficult to nest
result=`cat `which ls``     # Nesting causes error

Backticks are hard to nest and less readable.

βœ… Modern Syntax (Recommended)

date=$(date)                # Use $()
files=$(ls *.txt)           # More readable
result=$(cat $(which ls))   # Easy to nest

Use $() notation for readability and easy nesting.

🚫 Mistake 6: Arithmetic Operation Errors

❌ Error-causing Examples

result = $num1 + $num2      # Treated as string in shell
sum="$a + $b"               # Not calculated

Shell treats everything as strings by default.

βœ… Correct Calculation Methods

result=$((num1 + num2))     # Arithmetic expansion
sum=$(($a + $b))            # Calculate inside parentheses
let "result = num1 + num2"  # Use let command

Use $(()) or let for arithmetic operations.

πŸ’‘ Basic Rules to Prevent Mistakes

πŸ“ Writing Basics

  • Variable assignment: No spaces around =
  • Variable usage: Always quote "$var"
  • Complex variables: Use braces "${var}"

πŸ” Conditional Basics

  • Using [ ]: Always include internal spaces
  • String comparison: Quote both sides
  • Numeric comparison: Use -eq, -gt, -lt, etc.

βš™οΈ Execution and Testing

  • Incremental development: Add features gradually and test
  • Error checking: set -e to stop on error
  • Debugging: set -x to display command execution

πŸ› Debugging and Troubleshooting

Basic Debugging Techniques

#!/bin/bash

# Enable debug mode
set -x              # Display command execution
set -e              # Stop on error
set -u              # Error on undefined variables

# Check variable contents
echo "DEBUG: var = [$var]"

# Check file existence
if [ ! -f "$filename" ]; then
    echo "ERROR: File $filename not found" >&2
    exit 1
fi

Common Error Messages and Solutions

"command not found"
  • Unnecessary spaces in variable assignment
  • Missing execute permission β†’ chmod +x script.sh
  • Incorrect shebang
"syntax error"
  • Missing spaces inside [ ] in if statement
  • Quote mismatch
  • Missing keywords (then, fi, done, etc.)
"Permission denied"
  • No execute permission β†’ chmod +x script.sh
  • No write permission to file
  • No execute permission on directory

πŸš€ Next Steps

After mastering shell script basics, learn more advanced techniques in the practical edition:

πŸ“‹ What You'll Learn in Practical Edition

  • Functions - Code reuse and structure
  • Arrays - Efficient handling of multiple data
  • File Operations - Advanced read/write and file handling
  • Error Handling - Creating robust scripts
  • Practical Examples - Scripts for real work scenarios
Continue to Practical Edition β†’

πŸ“‹ Complete Shell Scripting Series

  1. Basics (This Article) - Variables, conditionals, loops, functions
  2. Practical Edition - Real-world scenarios, error handling, optimization
πŸ“’ About Affiliate Links

This site is a participant in the Amazon Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.co.jp. Product prices are not affected.

πŸŽ‰ Master Shell Scripting Through Practice

After gaining knowledge from books, practice hands-on with Penguin Gym Linux challenges to solidify your learning. Actually using variables, conditionals, and loops ensures skill development.