Hone

Lessons · Terminal · a space in a variable splits it

A space in a variable splits it

The shell splits an unquoted expansion on spaces BEFORE the command runs, so one value becomes two arguments.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

It is the bug that appears the first time real data has a space in it.

How to think about it

Quote expansions by default: "$var". It costs nothing on the ones that were fine anyway.

Worked example

p='disk full'; grep "$p" msgs.txt
Quoted: one argument, one match.
p='disk full'; grep -c "$p" msgs.txt
One match, counted rather than listed.
printf 'one two\n' > 'my file.txt'; wc -l 'my file.txt'
A filename with a space, quoted, is one argument.

Your turn

Search for a two-word phrase held in a variable.

p='a b'; grep "" orders.csv

The trap

On a machine you did not set up, assume every path has a space in it somewhere.

Practise a space in a variable splits it on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.