Copied to Clipboard
3. Always quote variable expansions ("$var")
Prevents word splitting + glob expansion.
name="a b * c"
echo $name # BAD: splits; globs expand
echo "$name" # GOOD: literal content
Tests: [ vs [[
4. [ is a builtin (POSIX test), [[ is a Bash keyword
[ "$x" = "abc" ] # POSIX test
[[ $x == abc ]] # Bash test, supports patterns, safer
5. [[ uses pattern matching unless the right side is quoted
x="hello"
[[ $x = h* ]] # true (pattern match)
[[ $x = "h*" ]] # false (literal match)
Globbing
6. Bash filename expansion uses globs, not regular expressions
❌ Not valid:
ls *.txt$
✔ Correct:
echo *.txt
7. Extended globs (+( ), !( ), etc.) require enabling
shopt -s extglob
echo +([0-9]).log
8. Globs can expand even when partially quoted
echo "*.txt" # no expansion → prints "*.txt"
echo *".txt" # expands → file1.txt file2.txt
Grouping & Control Flow
9. Group commands with {} when using && / ||
{ echo one; echo two; } && echo "group succeeded"
10. Grouping allows redirecting multiple commands at once
Redirect output:
{
echo line1
echo line2
} > out.txt
Redirect input:
{
read a
read b
echo "$a and $b"
} < file.txt
Pipelines & Subshells
11. Pipe (|) connects stdout → stdin
echo "hello" | tr a-z A-Z
12. Each side of a pipe runs in a subshell
x=1
echo hi | { read l; x=2; }
echo "$x" # still 1
13. Parentheses ( ) also create a subshell
x=1
( x=2 )
echo "$x" # prints 1
14. Braces { } do NOT create a subshell
x=1
{ x=2; }
echo "$x" # prints 2
Sourcing
15. source or . runs a script in the current shell
script.sh:
x=42
Using source:
x=1
source script.sh
echo "$x" # prints 42
Executing script directly:
x=1
./script.sh
echo "$x" # prints 1 (runs in subshell)
Dot form:
. script.sh