Command Line Advanced: Scripting and Administration
Shell Scripting Basics
In this lesson you will
- Create and run an executable Bash script
- Use variables, arguments, if statements and loops
- Quote variables correctly
Introduction
A shell script is a text file of commands. Anything you can type in the terminal you can save, repeat and share. Scripts turn boring jobs, such as backups, renaming files or deployments, into one command.
Your first script
Create a file named hello.sh:
Terminal
#!/usr/bin/env bash
echo "Hello, $1!"- The first line, the shebang, tells the system which program runs the file.
$1is the first argument given to the script.
Make it executable and run it:
Terminal
chmod +x hello.sh
./hello.sh SamHello, Sam!Variables
Terminal
name="Sam"
echo "Hello, $name"
today=$(date +%F) # store a command's output
echo "Backup for $today"No spaces around = when assigning. $(...) runs a command and uses its output.
Always quote variables
Without quotes, a value with spaces breaks into several words:
Terminal
file="my notes.txt"
rm $file # WRONG: tries to remove "my" and "notes.txt"
rm "$file" # right: removes "my notes.txt"Make double quotes around "$variable" a habit.
Quick quiz
Why should you put double quotes around variables such as $file in scripts?
Arguments
$1,$2and so on are the arguments.$#is how many were given.$@is all of them.
Conditions
Terminal
if [ "$#" -lt 1 ]; then
echo "Usage: $0 name"
exit 1
fi
if [ -f "$1" ]; then
echo "$1 is a file"
elif [ -d "$1" ]; then
echo "$1 is a folder"
else
echo "$1 does not exist"
fiCommon tests: -f file exists, -d directory exists, -z string is empty, and for numbers -eq, -lt, -gt. Spaces inside the brackets are required. In Bash, [[ ... ]] is a more forgiving alternative.
Loops
Terminal
for f in *.txt; do
echo "Found $f"
done
count=1
while [ "$count" -le 3 ]; do
echo "Round $count"
count=$((count + 1))
done$((...)) does arithmetic.
Reading input
Terminal
read -r -p "Your name? " answer
echo "Nice to meet you, $answer"Try it yourself
Write a script backup.sh that takes a file name as an argument, checks that it exists, and copies it to a folder called backup with today's date added to the name. Print a helpful message if no argument is given.
Summary
- A script starts with a shebang, and
chmod +xmakes it executable. - Use variables, arguments (
$1,$#),iftests andfororwhileloops. - Quote your variables, always.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading