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.

SANKOFA SANDBOX
learner:~$

This sandbox runs scripts, including arguments. Conditionals and loops are simplified here, but the shebang, arguments and chmod all behave properly.

Try it → Build a script that takes an argument: `echo '#!/bin/bash' > mk.sh`, then `echo 'mkdir -p $1/src' >> mk.sh` using single quotes so the dollar sign survives, then `chmod +x mk.sh`, then `./mk.sh testproject`, then `ls testproject`.

◈ Graded Task

Write a real tool. Create an executable script called scaffold.sh in your home directory that takes a project name as its argument and creates that directory with src and docs subdirectories inside it. Then run it to create a project called studio.

Checked against the filesystem you leave behind, not the commands you type, so any route that gets the job done counts. 5 visible and 3 hidden checks.

SANKOFA SANDBOX
learner:~$

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back