Line At A Time
Lesson 8: A Script That Does Real Work
A Script That Does Real Work Combine loops, variables and commands into a proper little tool.
1#!/bin/bash
2# backup.sh: copy every .txt file into a backup folder
3mkdir -p backup
4for file in *.txt
5do
6 cp "$file" backup/
7 echo "Backed up $file"
8done
9echo "All done!"
Terminal
$ ./backup.sh
Backed up pets.txt
Backed up shopping.txt
All done!
Every line, explained
#!/bin/bash
This first line is called the shebang (from "hash bang", the # and ! it starts with). It is not a comment: it tells the computer which program should read the rest of the file. #!/bin/bash means "run this with bash". Every bash script starts with this exact line.
# backup.sh: copy every .txt file into a backup folder
Anything after a # is a comment: bash ignores it completely. Comments are notes to the humans who read the script later, including you next month.
mkdir -p backup
The -p flag means "and do not complain if it already exists". That matters here: this script is meant to be run again and again, and a plain mkdir would fail the second time.
for file in *.txt
A for loop takes a list and runs the same lines once for each item in it. Each time round, the loop variable holds the current item. This time the list is not typed out: the * wildcard fills it in with every .txt file in the folder, so the script works on whatever it finds.
do
The body of the loop goes between do and done. Everything in between runs once per item.
cp "$file" backup/
Copy the current file into the backup folder. The quotes around "$file" matter: without them a file called my notes.txt would arrive as two separate words and the copy would fail.
echo "Backed up $file"
A script that says what it is doing is a script you can trust. Silence is fine for one command; for a loop over your files, say something.
done
The body of the loop goes between do and done. Everything in between runs once per item.
echo "All done!"
And that is a real tool: a handful of lines that will back up a hundred files as happily as two. Every big program started out looking like this.