Lesson 11.2: Variables, arguments and input
Storing values in variables (and the no-spaces rule), using them with $, command substitution $( ) and arithmetic $(( )), the arguments a script receives ($1, $#, $@, $0), reading input with read from a pipe or here-string, default values with ${var:-default}, trimming with ${var%.txt}, and why "$var" belongs in double quotes.
18 min
You will learn to
- Assign and use variables
- Capture a command's output with $( )
- Do integer arithmetic with $(( ))
- Use $1, $#, $@ and $0 in a script
- Read input with read
- Give a variable a default and trim its value
- Explain word splitting and quote variables
Key terms
- Variable
- A named place that holds a piece of text. Set with name=value (no spaces), read with $name or ${name}.
- Expansion
- The shell replacing $name, $(command), $((math)), ~ and wildcards with their values before it runs the command.
- Command substitution $( )
- Runs a command and inserts its output in place.
- Positional parameters
- The arguments given to a script or function: $1, $2 … ; $# is how many, $@ all of them ("$@" keeps each one separate), $0 the script's name.
- read
- Reads one line of input into one or more variables. -p shows a prompt, -r keeps backslashes as they are.
- Parameter expansion ${ }
- Forms of ${ } that change a value as it is read: ${v:-x} default if empty, ${v%pat} cut from the end, ${v#pat} cut from the start, ${#v} length.
- Word splitting
- After expanding an unquoted variable, the shell splits its value at spaces into separate arguments. Double quotes prevent it.
← Your first script · All lessons · Making decisions: if, test and case →