Using Positional Parameters
Introduction: From Hardcoded Values to Caller-Supplied Ones
Welcome back to Automating Tasks with zsh Scripts! We are now three units in, and tidy.zsh has grown from a straight list of commands into a script that inspects the world before touching it. There is still one thing it cannot do: work on a different folder. The values source_dir and label are frozen inside the file, so archiving a second folder means opening the script and editing it, which is exactly the kind of manual step we set out to remove.
This unit fixes that. The caller will hand those values to the script on the command line, and the same file will do two different jobs without a single edit. Four new pieces make this possible:
$1and$2, which carry the first and second arguments;$#, which counts how many arguments arrived;$0, which holds the name the script was called by;exit 1, which lets the script refuse a bad call and say that the work did not happen.
Preparing a Two-Folder Sandbox
Our workspace needs a small change from Unit 3: two source folders instead of one.
Two source folders, each holding a filled report.txt, one of them named with a space — two separate jobs for one script, and a quoting test as soon as that name travels from the command line into it.
Positional Parameters: $1, $2, $#, and $0
When we run a script with extra words after its name, zsh does not throw those words away; it stores them in numbered parameters. Imagine a tiny script whose only job is to report what it received.
Three details are worth keeping in mind right away:
- Positional parameters are numbered by position, not by name. Swap the two words on the command line, and
$1becomesexpenses;zshhas no idea what either value is supposed to mean. - A parameter that was never supplied expands to nothing at all.
$2on a one-argument call is simply empty; there is no error, which is precisely why we need to check the count ourselves. - Every one of them gets double quotes, exactly like the variables from Unit 2, so a value containing a space remains a single argument.
