Running Your First Script
Introduction: From Typing Commands to Saving Them
Welcome to Automating Tasks with zsh Scripts, the first unit of four ... well, of six. Everything we have typed so far — mkdir -p, cp, and echo — worked beautifully once and then vanished the moment the prompt returned. A script fixes that: It is nothing more mysterious than those same commands saved in a file so we can replay them whenever we like.
Throughout this unit, we will work with one small routine: create an archive directory, copy report.txt into it, and print a short confirmation. That routine lets us answer the two questions that matter today:
- How do we save a routine into a file?
- How do we run that file?
Setting Up the Workspace
Scripts act on real files, so before writing one, we need a predictable place to experiment. Everything here uses tools from the earlier courses.
Line by line:
mkdir -pcreates the whole path and stays quiet if it already exists; then wecdinto it.printf 'draft notes\n' > report.txtgives us a small input file to copy around.rm -R archive 2>/dev/nulldeletes any leftoverarchivedirectory from a previous run, sending the "no such file" complaint to/dev/nullso a first run looks just as clean as a tenth run.
This is a sandbox, nothing more; the interesting part starts next.
Writing the Script File and the Shebang Line
Now we save our routine into a file. Rather than opening an editor, we use a quoted heredoc, as you may recall from the redirection lesson.
Quoting 'EOF' is essential: It tells the shell to store every line literally, so nothing is expanded while we are merely writing the file. The three commands inside are ordinary ones we already know. The first line, however, is new: #!/bin/zsh is the shebang, made of the #! marker plus the absolute path to the interpreter. To the shell, it looks like a comment, but to the operating system, it is a real instruction: "run this file with /bin/zsh." The .zsh extension is only a naming convention for humans.
