Linux Command Line · Lesson 36 of 43
Your first Bash script
Write, save and run your first Bash script: the shebang line, making it executable, comments, running it by path, and a safer starting template.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will turn commands you have been typing into a program you can save and run again. Scripting is where the command line pays off: a task you do twice becomes a task you do once and automate forever.
What a script is
A shell script is a plain text file containing commands, exactly as you would type them, run one after another. Anything you can do at the prompt can go into a script, and the shell's features, such as variables, conditions and loops, make it into a small programming language. This course uses Bash, the most common shell.
Write the script
Create a file with a text editor, or, as we do here, with cat and a here document so that the whole lesson fits in one block:
cd ~/project
cat > hello-script.sh <<'SCRIPT'
#!/bin/bash
# Print a greeting and a little information.
echo "Hello from a script"
echo "Today's folder is: $(basename "$PWD")"
SCRIPT
cat hello-script.sh#!/bin/bash
# Print a greeting and a little information.
echo "Hello from a script"
echo "Today's folder is: $(basename "$PWD")"The quoted marker 'SCRIPT' stops the shell from expanding $(...) while writing the file, so the text is stored as it is. Two parts deserve a closer look.
The first line, #!/bin/bash, is the shebang (also called hashbang). The two characters #! followed by a path tell the system which program interprets the file. For portability, you will often see #!/usr/bin/env bash, which finds Bash through PATH.
The second line begins with #, so it is a comment: everything from # to the end of a line is ignored. Use comments to say why something is done.
Run it
Right after creation, the file is not executable. Running it directly fails, but handing it to Bash works because Bash only needs to read the file:
./hello-script.sh
bash hello-script.shbash: ./hello-script.sh: Permission denied
Hello from a script
Today's folder is: projectThe first command failed with a permission error, and the second worked. To make it directly executable, add the execute permission once, and then run it with a path. The ./ is needed because the current folder is not in PATH:
chmod +x hello-script.sh
./hello-script.shHello from a script
Today's folder is: projectTo run it from any folder by name, move it into a folder that is in your PATH, such as ~/bin, as you saw in the lesson on environment variables.
Scripts run in a child process
When you run ./script.sh, the shell starts a new process to run it. That process inherits copies of your exported variables and your current folder, but changes it makes stay inside it. Watch what happens to the folder:
cd ~/project
printf '#!/bin/bash\ncd /tmp\npwd\n' > go-tmp.sh
chmod +x go-tmp.sh
./go-tmp.sh
pwd/tmp
/home/learner/projectThe script changed to /tmp, but your shell stayed in project. If you want a script to change your shell's folder or set your variables, run it with source script.sh (or . script.sh), which executes the lines in your current shell. That is how ~/.bashrc works.
Exit status
Every command finishes with an exit status: 0 means success, anything else means failure. A script's exit status is that of its last command, unless it calls exit N. You can see the status of the last command in $?:
cd ~/project
printf '#!/bin/bash\necho "working"\nexit 3\n' > fail.sh
chmod +x fail.sh
./fail.sh
echo "status: $?"working
status: 3Other programs, such as cron, make and if, decide what to do next based on this number, so a script should exit 0 on success and non-zero on failure.
A starting template
Most real scripts begin with a few safety lines. You will understand each in the coming lessons:
#!/bin/bash
# backup.sh - copy the project folder to a dated backup.
set -euo pipefail
echo "starting"set -e stops the script at the first failing command, set -u treats unset variables as errors, and set -o pipefail makes a pipeline fail if any stage fails. They turn silent mistakes into visible ones, and they are a good habit for scripts that change things.
Where scripts go wrong
A few things trip up nearly everybody:
- Windows line endings. A script saved with CRLF endings fails with
bad interpreter: No such file or directorybecause the shebang ends with a hidden carriage return. Convert withdos2unix script.sh, or with GNUsed:sed -i 's/\r$//' script.sh(BSD and macOSsedneed a different form). - Spaces around
=in assignments, such asname = Asha, which runs a command calledname. - Unquoted variables.
rm $filebreaks when the name contains a space; writerm "$file". - Missing shebang. Without it, the file may be run by a different shell than you intended.
Common mistakes
Forgetting chmod +x. You get Permission denied.
Running script.sh without ./. The shell looks in PATH and reports command not found.
Expecting a script to change your folder. It runs in a child process; use source.
Not testing small steps. Add a few lines at a time and run the script after each change.
Exercise
Write info.sh that prints your user name, the current date with date +%F, and the number of files in the current folder. Make it executable and run it two ways. Then make it exit with status 0 when the folder has files and status 1 when it does not, and print the status with echo $?.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.