Lesson 19: Shell Scripts
The tar command from the previous lesson works — but when it runs in cron you can't tell if it succeeded. We wrap it in a bash script: #!/bin/bash on the first line tells which interpreter to use. DEST=/backups defines a variable; $DEST uses it. chmod +x backup.sh adds execute permission. $? after a
A script is like a written recipe. #!/bin/bash says 'cook with bash'. DEST=/backups saves an address on a note. $DEST reads the note. chmod +x says 'you can cook this'. $? is the taste after cooking — 0 = good.
- shebang (#!/bin/bash)
- The first line of a script — tells which interpreter runs it. #! marks it, /bin/bash is the path to bash. Without a shebang, the OS guesses the interpreter.
- bash variable
- NAME=value defines (no spaces). $NAME reads the value. "$NAME" in double quotes guards against word splitting if the value contains spaces.
- exit code ($?)
- A code every command returns: 0 = success, anything else = failure. $? holds the code from the last command. Must be read immediately before another command overwrites it.
- chmod +x
- Adds execute permission to a script. Without it, ./script.sh returns 'Permission denied'. chmod +x script.sh enables ./script.sh; bash script.sh also works without chmod +x.