Skip to content
Bash

Variables and Arrays in Bash

Assign variables, use command substitution, and work with arrays in Bash.

By EZ4Code Team
variablearraybeginner

Code

#!/bin/bash

# String variables
name="Alice"
greeting="Hello, $name"
echo "$greeting"           # Hello, Alice

# Command substitution
current_date=$(date +%Y-%m-%d)
files_count=$(ls | wc -l)

# Default values
echo "${USER:-guest}"      # use 'guest' if USER unset

# Arrays
fruits=("apple" "banana" "cherry")
echo "${fruits[0]}"        # apple
echo "${fruits[@]}"        # all
echo "${#fruits[@]}"       # length: 3

# Read user input
read -p "Enter your name: " username
echo "Hi, $username"

Explanation

Covers variable assignment (no spaces around =), command substitution with $(), and default values with ${VAR:-fallback}. Indexed arrays use parentheses and are accessed via ${arr[0]} or ${arr[@]} for all elements. read -p prompts for user input during script execution.

More Bash Snippets