Bash Basics: Variables, Quoting & Output

Variables, the three kinds of quoting, command substitution, arithmetic and printf.

Bash variables hold strings, and almost every bug in shell scripts comes from how Bash splits and expands them. Learn the quoting rules first and most problems never happen.

First script

board="rev_b" assigns; there must be no spaces around =.

Double quotes expand $variables; single quotes keep the text exactly as written.

touch "$file_name" creates one file named 'test report.txt'; without quotes it would create two files, 'test' and 'report.txt'.

$(command) captures a command's output; $(( ... )) does integer arithmetic.

printf formats exactly: %-12s left-aligned text, %6.2f a number with 2 decimals, %04d zero-padded.

The golden rule

name = "rev_b" With spaces, Bash runs a command called name with the arguments = and rev_b.

If file is 'test report.txt', the unquoted version tries to delete 'test' and 'report.txt'.

What is the difference between '$HOME' and "$HOME"?

In single quotes $HOME is printed literally; in double quotes it is replaced by the home directory path.

How do you store the number of lines in app.log in a variable?

lines=$(wc -l < app.log)