Everything you have typed at the command line so far can be saved in a file and replayed automatically. That file is a shell script, and scripting is where the Linux command line turns from a toolbox into a superpower. In this lesson you will write your first Bash script, learn variables, conditionals, loops and command-line arguments, and pick up the habits that keep scripts safe and readable.
A script is just a text file that starts with a shebang line telling the system which interpreter to use. Create a file called hello.sh:
#!/bin/bash
echo "Hello from a script!"
echo "Today is $(date +%A)"Make it executable and run it:
chmod +x hello.sh
./hello.shThe $(...) syntax is command substitution: Bash runs the inner command and replaces the expression with its output.
Variables are assigned without spaces around the equals sign and read with a dollar sign. Scripts also receive positional arguments: $1 is the first argument, $2 the second, $# is the argument count, and $@ expands to all of them.
#!/bin/bash
name=${1:-world} # use first argument, default to 'world'
echo "Hello, $name"
echo "You passed $# argument(s)"Always wrap variable expansions in double quotes, as in "$name". Unquoted variables are split on spaces, which is one of the most common sources of shell script bugs.
The if statement tests a condition using the [[ ... ]] construct. Comparison operators differ for strings and numbers: use == and != for strings, and -eq, -lt, -gt for integers. File tests such as -f (file exists) and -d (directory exists) are extremely useful:
#!/bin/bash
file="$1"
if [[ -z "$file" ]]; then
echo "Usage: $0 <filename>" >&2
exit 1
elif [[ -f "$file" ]]; then
echo "$file exists and has $(wc -l < "$file") lines"
else
echo "$file does not exist"
fiExiting with a non-zero status signals failure, which matters when other scripts or CI pipelines call yours.
Loops let you apply the same commands to many items. The for loop iterates over a list, and while loops run until a condition fails:
#!/bin/bash
for f in *.log; do
gzip "$f"
echo "Compressed $f"
done
count=1
while [[ $count -le 3 ]]; do
echo "Attempt $count"
count=$((count + 1))
doneThe $(( ... )) syntax performs integer arithmetic.
Professional scripts usually begin with a safety line: set -euo pipefail. The -e flag stops the script on the first error, -u treats undefined variables as errors, and pipefail makes a pipeline fail if any command in it fails. Combined with quoting every variable and checking arguments before using them, this catches most mistakes early instead of letting a broken script keep running and do damage.
In the final lesson of this course, you will take your skills over the network: SSH, scp and working with remote servers.