Fundamentals 24 min read

Unlock Bash Mastery: Variables, Loops, Functions, and More Explained

This article provides a comprehensive guide to Bash programming, covering variable types and naming rules, assignment and quoting, environment and positional variables, arithmetic and logical operations, conditional statements, loops, functions, arrays, string manipulation, signal handling, and essential command‑line utilities for Linux system scripting.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Unlock Bash Mastery: Variables, Loops, Functions, and More Explained

Introduction to Bash Programming

During Linux learning you inevitably encounter Bash programming (shell scripting). A shell is a command‑language interpreter; a shell script is a collection of Linux commands executed in a predefined order to perform complex system‑management tasks, similar to Windows batch files.

Variables

Variable categories

Local variables – effective only in the current shell process and its children.

Environment variables – exported to the current shell and its child processes.

Positional parameters – $1, $2, …, ${10}.

Special variables – $#, $*, $?, $-, $@, etc.

Assignment syntax: VAR_NAME=VALUE Variable reference uses ${VAR_NAME}. Quoting rules:

"" – weak quoting, variables are expanded.
'' – strong quoting, characters are taken literally.

Environment variable commands:

export VAR_NAME=VALUE   # define and export
export VAR_NAME          # export existing variable
unset VAR_NAME           # remove variable
readonly VAR_NAME        # make read‑only

Local variable inside a function: local VAR_NAME=VALUE Positional parameters are accessed as $1, $2, …

Variable Naming Rules

Do not use reserved keywords.

Only letters, digits, and underscores; cannot start with a digit.

Names should be meaningful.

Variable Types

Numeric: integers (exact) and floating‑point (approximate).

String: char, string.

Boolean: true, false.

Type conversion can be explicit or implicit; Bash performs implicit conversion when needed.

Bash Configuration Files

Configuration files set local variables and command aliases.

Profile files (for interactive login shells): /etc/profile, /etc/profile.d/*.sh, ~/.bash_profile Bashrc files (for non‑interactive shells): /etc/bashrc,

~/.bashrc

Script Format and Execution

The first line must be the shebang to specify the interpreter: #!/bin/bash # shebang Comments start with # and are ignored by the interpreter.

Execution options:

bash -n script.sh   # syntax check
bash -x script.sh   # step‑by‑step debug

Arithmetic and Logical Operations

Define integer variables:

let a=3
declare -i b=5

Arithmetic evaluation methods:

let result=EXPR
result=$[EXPR]
result=$((EXPR))
result=$(expr $num1 + $num2)

Operators:

+ addition, - subtraction, * multiplication, / integer division, % modulus, ** exponentiation.

Logical: && (and), || (or), ! (not).

Conditional Tests

Integer comparisons:

[ $a -gt $b ]   # greater than
[ $a -lt $b ]   # less than
[ $a -ge $b ]   # greater or equal
[ $a -le $b ]   # less or equal
[ $a -eq $b ]   # equal
[ $a -ne $b ]   # not equal

String comparisons:

[[ "$str1" > "$str2" ]]   # lexicographic greater
[[ "$str1" == "$str2" ]]  # equal
[ -n "$str" ]   # non‑empty
[ -z "$str" ]   # empty

File tests (e.g., -f FILE for regular file, -d FILE for directory, etc.).

Combined conditions use &&, ||, and !.

If Statements

# Single‑branch
if test; then
    # commands
fi

# Double‑branch
if test; then
    # true branch
else
    # false branch
fi

# Multi‑branch
if cond1; then
    # branch1
elif cond2; then
    # branch2
else
    # default branch
fi

Case Statement

case $var in
    pattern1) commands ;; 
    pattern2) commands ;; 
    *) default commands ;; 
esac

Loops

For Loops

# List form
for var in list; do
    # body
done

# C‑style
for ((i=0; i<=100; i++)); do
    # body
done

While Loop

while condition; do
    # body
done

Until Loop

until condition; do
    # body
done

Loop control commands: break (exit loop), continue (skip to next iteration).

Functions

function func_name {
    # body
}

func_name() {
    # body
}

Functions receive parameters as $1, $2, … and can return a status with return N. The exit status of the last command is the function’s return value unless overridden.

Signal Trapping

# Execute commands when a signal is received
trap 'commands' SIGINT

# Restore default handling
trap SIGTERM

# Ignore a signal
trap '' SIGUSR1

Arrays

Indexed array declaration: declare -a ARRAY_NAME Associative array declaration: declare -A MAP_NAME Assigning values:

a[0]=value
arr=(red blue yellow)
arr=([0]=green [3]=red [2]=blue)
read -a ARRAY   # read from input

Accessing elements: ${ARRAY[index]}. Length: ${#ARRAY[@]}. Slicing: ${ARRAY[@]:offset:number}. Adding elements: ARRAY[${#ARRAY[@]}]=new. Deleting: unset ARRAY[index].

String Manipulation

Substring extraction:

${string:offset:length}
${string: -length}   # last N characters

Pattern removal:

${var#*word}   # shortest match from left
${var##*word}  # longest match from left
${var%word*}   # shortest match from right
${var%%word*}  # longest match from right

Search‑and‑replace:

${var/pattern/repl}      # first occurrence
${var//pattern/repl}     # all occurrences
${var/#pattern/repl}   # if pattern at start
${var/%pattern/repl}   # if pattern at end

Case conversion:

${var^^}   # to upper case
${var,,}   # to lower case

Useful Commands

Temporary files/directories:

mktemp /tmp/tmp.XXX          # create temp file
mktemp -d /tmp/tmpdir.XXX    # create temp directory

Enhanced copy/install:

install -m 644 source dest          # copy with mode
install -o user -g group source dest
install -d /path/to/dir            # create directory

These concepts form the foundation for effective Bash scripting and Linux system automation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

linuxBashfunctionsVariablesShell scriptingLoops
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.