Skip to content
Laviyx Learn

Try

Bash Scripting Practice

Practise Bash scripting: variables, conditions, loops, functions, arguments, arrays and safe scripts. Every solution has been run on Ubuntu and shows its real output.

Intermediate12 problemsUpdated

Review first: Your First Bash Script, Variables and Quoting, Conditions with if and case, Loops, Functions, Arguments and Exit Codes, Arrays and String Handling, Writing Safe Scripts

  1. 1.Calculate a bill

    Beginner

    With price=250 and qty=4, print the subtotal and the total after adding a 10 percent tip, as whole numbers.

    Show hint

    $(( )) does integer arithmetic.

    Show solution
    Terminal
    price=250
    qty=4
    sub=$((price * qty))
    total=$((sub + sub / 10))
    echo "Subtotal: $sub"
    echo "Total: $total"
    Output
    Subtotal: 1000
    Total: 1100
  2. 2.Even or odd

    Beginner

    Loop from 1 to 4, printing whether each number is even or odd.

    Show hint

    (( n % 2 == 0 )).

    Show solution
    Terminal
    for n in {1..4}; do
      if (( n % 2 == 0 )); then
        echo "$n even"
      else
        echo "$n odd"
      fi
    done
    Output
    1 odd
    2 even
    3 odd
    4 even
  3. 3.Check a path

    Beginner

    Write a function kind that prints file, folder or missing for a path. Test it on /etc/hostname, /etc and /nothing.

    Show hint

    -f and -d.

    Show solution
    Terminal
    kind() {
      if [[ -f "$1" ]]; then
        echo "file"
      elif [[ -d "$1" ]]; then
        echo "folder"
      else
        echo "missing"
      fi
    }
    kind /etc/hostname
    kind /etc
    kind /nothing
    Output
    file
    folder
    missing
  4. 4.Change file extensions

    Intermediate

    Rename every .jpeg file in the folder to .jpg, and list the folder.

    Starter code (Terminal)
    touch one.jpeg two.jpeg
    Show hint

    ${f%.jpeg} removes the old extension.

    Show solution
    Terminal
    for f in *.jpeg; do
      mv "$f" "${f%.jpeg}.jpg"
    done
    ls
    Output
    one.jpg
    two.jpg
  5. 5.Read a CSV file

    Intermediate

    Read staff.csv line by line, skip the header, and print name earns salary for people in Pune.

    Starter code (Terminal)
    cat > staff.csv <<'EOF'
    name,city,department,salary
    Asha,Hyderabad,Engineering,90000
    Ravi,Pune,Sales,55000
    Meena,Hyderabad,Engineering,105000
    Karan,Chennai,Support,42000
    Divya,Pune,Engineering,88000
    Arjun,Hyderabad,Sales,61000
    EOF
    Show hint

    while IFS=, read -r ... with tail -n +2.

    Show solution
    Terminal
    while IFS=, read -r name city dept salary; do
      if [[ "$city" == "Pune" ]]; then
        echo "$name earns $salary"
      fi
    done < <(tail -n +2 staff.csv)
    Output
    Ravi earns 55000
    Divya earns 88000
  6. 6.Add all arguments

    Intermediate

    Write a function sum that adds up all its arguments. Call it with 5, 10 and 20.

    Show hint

    Loop over "$@".

    Show solution
    Terminal
    sum() {
      local total=0
      for n in "$@"; do
        total=$((total + n))
      done
      echo "$total"
    }
    sum 5 10 20
    Output
    35
  7. 7.Check arguments

    Intermediate

    Write greet.sh, which prints a usage message to stderr and exits with code 2 if it has no argument, and otherwise greets the name given. Test both.

    Show hint

    $# holds the number of arguments.

    Show solution
    Terminal
    cat > greet.sh <<'EOF'
    #!/bin/bash
    if [[ $# -lt 1 ]]; then
      echo "Usage: $0 <name>" >&2
      exit 2
    fi
    echo "Hello, $1"
    EOF
    bash greet.sh
    echo "Exit code: $?"
    bash greet.sh Asha
    Output
    Usage: greet.sh <name>
    Exit code: 2
    Hello, Asha
  8. 8.Count words with an associative array

    Intermediate

    Count how many times each word appears in red blue red green red, and print the counts sorted by word.

    Show hint

    declare -A.

    Show solution
    Terminal
    declare -A count
    for word in red blue red green red; do
      count[$word]=$(( ${count[$word]:-0} + 1 ))
    done
    for word in "${!count[@]}"; do
      echo "$word ${count[$word]}"
    done | sort
    Output
    blue 1
    green 1
    red 3
  9. 9.Split a path

    Intermediate

    For /var/log/nginx/access.log, print the folder, the file name, and the extension, using parameter expansion only.

    Show hint

    ${f%/*}, ${f##*/} and ${f##*.}.

    Show solution
    Terminal
    f="/var/log/nginx/access.log"
    echo "${f%/*}"
    echo "${f##*/}"
    echo "${f##*.}"
    Output
    /var/log/nginx
    access.log
    log
  10. 10.Disk usage alert

    Intermediate

    Write a function check that takes a percentage, prints ALERT and returns 1 at 90 or above, and otherwise prints OK. Test it with 45 and 93, printing the status each time.

    Show hint

    return 1 sets the status.

    Show solution
    Terminal
    check() {
      if (( $1 >= 90 )); then
        echo "ALERT"
        return 1
      fi
      echo "OK"
    }
    check 45; echo "Status: $?"
    check 93; echo "Status: $?"
    Output
    OK
    Status: 0
    ALERT
    Status: 1
  11. 11.Retry a command

    Advanced

    Write a function retry that runs a command up to 3 times, stopping when it succeeds. Test it with a command that fails twice, by counting attempts in the file tries.

    Starter code (Terminal)
    cat > flaky.sh <<'EOF'
    #!/bin/bash
    n=$(cat tries 2> /dev/null || echo 0)
    n=$((n + 1))
    echo "$n" > tries
    [[ $n -ge 3 ]]
    EOF
    Show hint

    Loop with for i in 1 2 3, and return 0 on success.

    Show solution
    Terminal
    retry() {
      local i
      for i in 1 2 3; do
        if "$@"; then
          echo "Worked on attempt $i"
          return 0
        fi
      done
      echo "Failed"
      return 1
    }
    retry bash flaky.sh
    Output
    Worked on attempt 3
  12. 12.Clean up with trap

    Advanced

    Write a script with set -euo pipefail that makes a temporary file, removes it with a trap, and fails on purpose. Show that the file is gone afterwards.

    Show hint

    trap 'rm -f "$tmp"' EXIT.

    Show solution
    Terminal
    cat > job.sh <<'EOF'
    #!/usr/bin/env bash
    set -euo pipefail
    tmp=$(mktemp)
    trap 'rm -f "$tmp"' EXIT
    echo "$tmp" > where.txt
    false
    echo "Never printed"
    EOF
    bash job.sh
    echo "Exit code: $?"
    [[ -e "$(cat where.txt)" ]] && echo "Still there" || echo "Removed"
    Output
    Exit code: 1
    Removed