Arguments, Variables, and Decisions
Arguments make a script reusable. Inside a script, $1 is the first argument, $2 the second, and $# is how many there were.
`
#!/bin/bash
mkdir -p $1/src $1/docs
echo Created $1
`
Run as ./new.sh archive, and $1 becomes archive. The same script now builds any project you name, which is the difference between a shortcut and a tool.
✦ Quote your variables
Write "$1" rather than $1 in nearly every case. If someone passes an argument containing a space, an unquoted variable splits into two arguments and the script does something surprising. Quoting is the difference between a script that works and a script that works until someone types a project name with a space in it.
Deciding and repeating. Two structures cover most of what a script needs.
`
if [ -d "$1" ]; then
echo That already exists
fi
for f in *.txt; do
echo Found $f
done
`
The square brackets are a test. -d asks is this a directory, -f asks is this a file, -z asks is this string empty. Checking that a required argument was actually given, with -z, is the single most valuable line you can add to a script.
Where this is going. Everything you have written down since module 3 is raw material. The project scaffold, the backup routine, the audit pipeline. Each one is a script waiting to be saved, and the collection of them is your own productivity system rather than a set of exercises.
Mark this lesson complete
Signed in, your progress follows you to every device.