Master Bash Variable Types and Command Substitution: A Practical Guide
This article explains Bash variable scopes, assignment methods, command substitution, positional and special parameters, arithmetic operations, test expressions, exit codes, and common pitfalls, providing clear examples and best‑practice tips for reliable shell scripting.
Variable Types in Bash
Local variables are only valid in the current shell and are not inherited by child shells, while environment variables are exported to child shells.
Assignment and Substitution
Assign a value with name=value. Use backticks `command` or $(command) for command substitution; when nesting, the outer substitution should use $(...) to avoid ambiguity.
Examples of Command Substitution
#!/bin/bash
Sum=$(echo `seq $1 $2` | tr " " "+" | bc)
echo "$1 to $2 sum is: $Sum"Using backticks for the inner command works, but wrapping the whole expression with $(...) is safer.
Variable Reference and Management
Reference a variable with $name or ${name}.
List all defined variables: set.
Delete a variable: unset name.
Environment Variables
Export a variable to child shells: export name=value or declare -x name=value.
Common built‑in environment variables:
PATH, SHELL, USER, UID, HISTSIZE, HOME, PWD, OLDPWD, HISTFILE, PS1.
Special Variables
Positional parameters: $1, $2, … (access script arguments).
All arguments as a single string: $*.
All arguments as separate words: $@.
Number of arguments: $#.
Exit status of last command: $? (0 = success, 1‑255 = failure).
Script name: $0.
Read‑Only Variables
Declare a read‑only variable with readonly name=value or declare -r name=value; it cannot be modified or unset.
Arithmetic Operations
Supported operators: +, -, *, /, %, ** (exponent).
Methods to evaluate expressions:
let var=expression var=$[expression] var=$((expression)) var=$(expr arg1 op arg2)(spaces required).
Example using expr: echo $(expr 5 \* 2 - 1) # outputs 9 Declare an integer variable: declare -i var=10.
Generate random numbers: echo $[RANDOM%50] (0‑49) or echo $[RANDOM%50+1] (1‑50).
Aggregating Commands and Sub‑Shells
Parentheses create a sub‑shell: (commands). Using exit inside a sub‑shell terminates only that sub‑shell.
Exit Status Codes
0 indicates success; any value 1‑255 indicates failure. The variable $? holds the status of the most recent command. An explicit exit N ends the script with status N.
Conditional Tests
Use the test command or [ expression ] / [[ expression ]] syntax.
Numeric tests: -gt, -ge, -lt, -le, -eq, -ne.
String tests: ==, !=, >, <, =~ (pattern match), -z "string" (empty), -n "string" (non‑empty).
File existence and type: -e or -a: file exists. -f: regular file. -d: directory. -b: block device. -c: character device. -h or -L: symbolic link. -p: named pipe. -S: socket.
Permission tests: -r (read), -w (write), -x (execute), -g (set‑gid), -u (set‑uid), -k (sticky).
Size test: -s (non‑empty file).
File descriptor test: -t fd (fd is associated with a terminal).
Combined conditions:
Logical AND: COMMAND1 && COMMAND2 or EXPRESSION1 -a EXPRESSION2.
Logical OR: COMMAND1 || COMMAND2 or EXPRESSION1 -o EXPRESSION2.
Negation: ! COMMAND or ! EXPRESSION.
Practical Argument Handling
Example scripts demonstrating $* vs $@ and how quoting affects argument splitting.
#!/bin/bash
# arg1.sh
echo "1st is $1"
echo "2nd is $2"
echo "all args are \"$*\""Running the script with ./arg1.sh "$*" or ./arg1.sh "$@" shows the difference in how arguments are passed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
