Intermediate · 8 min · practise every command in the built-in terminal

Variables in Bash Scripts

Declaring variables

#!/bin/bash
NAME="IVski"           # No spaces around =!
NUMBER=42
FILES=$(ls -la)         # Command substitution
DATE=$(date +%Y-%m-%d)

⚠️ No spaces around =! NAME = "value" will fail.

String operations

NAME="IVski"
echo ${#NAME}            # Length: 5
echo ${NAME,,}           # Lowercase: ivski
echo ${NAME^^}           # Uppercase: IVSKI
echo ${NAME:0:2}         # Substring: IV
echo ${NAME/sk/SK}       # Replace: IVSKi

Default values

NAME=${1:-"World"}       # Use $1 or default to "World"
: ${CONFIG:="default"}   # Set if unset

Arrays

FRUITS=("apple" "banana" "cherry")
echo ${FRUITS[0]}        # apple
echo ${FRUITS[@]}        # All elements
echo ${#FRUITS[@]}       # Count: 3
FRUITS+=("date")         # Append

for fruit in "${FRUITS[@]}"; do
    echo "$fruit"
done

Arithmetic

A=10
B=3
echo $((A + B))          # 13
echo $((A * B))          # 30
echo $((A / B))          # 3 (integer division)
echo $((A % B))          # 1 (remainder)
((COUNT++))              # Increment

Practice tasks

  1. Write a script that stores your name in a variable and prints a greeting
  2. Store your favorite color in a variable and print a sentence using it
  3. Update the value of an existing variable and print the new value

Commands in this lesson

Shell Scripting