variables

A variable in Bash holds a string Everything else is a trick played with strings

Assignment and use

name="0x1RIS"
printf '%s\n' "$name"

No spaces around = Quotes around the expansion Skip either and you will eventually feed a filename with spaces into a command that splits it apart

Expansion

printf '%s\n' "${name^^}"
printf '%s\n' "${#name}"

Output:

0X1RIS
6

^^ uppercases # counts characters These are Bash features, not external commands

Defaults

printf '%s\n' "${name:-fallback}"

:- uses the fallback when the variable is unset or empty ${var:=value} assigns the fallback as well Use :- when you only need a value for this one line

Arrays

items=(one two three)
printf '%s\n' "${#items[@]}"
printf '%s\n' "${items[1]}"

Output:

3
two

Indexing starts at zero ${#items[@]} counts elements

Quoting rule

Double quotes allow expansion Single quotes stop it entirely Unquoted expansions invite word splitting and globbing Default to double quotes and remove them only when you need the split

Next

Decisions and loops in 07 control

Posted