Your First Scripts: Arguments, Exit Codes, and Conditionals
Write Bash scripts that take arguments, validate their input, return meaningful exit codes, and branch with test, [[ ]], if and case, built around a real log-archiving tool.
By The Dark DebuggerUpdated 36 min read
This is the first article in the Scripting section. We'll turn commands you already know into scripts that take arguments, check them, report success or failure through exit codes, and make decisions with if and case. You should be comfortable with variables and quoting from Variables, Quoting, and the Environment and with &&, || and $? from Command Substitution, Chaining, and Exit Codes. Loops and functions come next, in Loops, Functions, and Reading Input.
Why write scripts at all
Picture an application that writes a new log file every day into one directory. Once a week somebody types a long find … -mtime +7 … command to bundle the old files into a tarball and delete them. One week they mistype the directory. Another week they forget the -name '*.log' filter and archive the application's config file along with the logs.
A script fixes that. The command is written once, it checks its input before touching anything, it tells you (and cron, and your CI system) whether it worked, and a colleague can run it without knowing the incantation. Over this article we'll build exactly that tool, archive-logs.sh, one concept at a time.
A first script
A script is a text file of commands. Here is a small one that prints a status line about the machine:
#!/usr/bin/env bash
# today.sh - print a short status summary for this machine
echo "Date: $(date +%F)"
echo "User: $USER"
echo "Uptime: $(uptime -p)"Save it as today.sh and try to run it:
ls -l today.sh
./today.sh-rw-r--r-- 1 sid sid 155 Nov 9 21:25 today.sh
bash: ./today.sh: Permission deniedA new file is not executable. The -rw-r--r-- permissions have no x, so the kernel refuses to run it. Add the execute bit (see File Permissions and Ownership for what chmod does in detail):
chmod +x today.sh
./today.shDate: 2026-11-09
User: sid
Uptime: up 14 minutesWhy ./today.sh and not just today.sh? Typing a bare name makes Bash search the directories in $PATH, and the current directory is not in $PATH (deliberately, so a file called ls in a downloaded folder can't hijack your ls):
today.shbash: today.sh: command not foundThe ./ says "the file right here". Once a script is finished, people usually copy it into a directory that is on $PATH, such as ~/bin or /usr/local/bin, and then the bare name works.
The shebang line
The first line, #!/usr/bin/env bash, is the shebang. When you execute a file, the kernel looks at its first two bytes. If they are #!, the rest of the line names the interpreter that should run the file. Without a shebang, which program interprets your script depends on whoever starts it.
There are three shebangs you'll see on Bash-era scripts:
| Shebang | What runs the script | When to use it |
|---|---|---|
#!/usr/bin/env bash | the first bash found on $PATH | Default choice. Works where Bash lives somewhere other than /bin, for example a newer Bash installed by Homebrew on macOS, whose own /bin/bash is the ancient 3.2. |
#!/bin/bash | exactly /bin/bash | Fine on Linux servers; immune to a strange $PATH, which some people prefer for scripts run as root. |
#!/bin/sh | the system's POSIX shell | Only for scripts that avoid every Bash feature. On Debian and Ubuntu sh is dash, not Bash. |
That last row is where people get hurt. This script uses [[ ]], a Bash feature we'll meet shortly, but declares sh:
#!/bin/sh
name="report.log"
if [[ $name == *.log ]]; then
echo "$name is a log file"
fi./check-ext.sh
bash check-ext.sh
ls -l /bin/sh./check-ext.sh: 3: [[: not found
report.log is a log file
lrwxrwxrwx 1 root root 4 Mar 31 2024 /bin/sh -> dashExecuted directly, the shebang picked dash, which has no [[. Run as bash check-ext.sh, the shebang is ignored entirely (it is just a comment to Bash) and the script works. If you write Bash, say so in the shebang.
One more trap: on Linux, everything after the interpreter path is passed as a single argument. So you can't sneak options in after env:
printf '#!/usr/bin/env bash -e\necho "strict mode?"\n' > env-args.sh
chmod +x env-args.sh
./env-args.sh/usr/bin/env: ‘bash -e’: No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang linesenv went looking for a program literally named bash -e. Put options inside the script instead (set -e on line 2); we cover those options properly in Error Handling, Traps, and Debugging.
Three ways to run a script
| Command | Needs chmod +x? | Uses the shebang? | Where it runs |
|---|---|---|---|
./script.sh | yes | yes | a new child process |
bash script.sh | no | no (Bash is named explicitly) | a new child process |
source script.sh or . script.sh | no | no | your current shell |
The difference between the first two and source matters more than it looks. This script changes directory and sets a variable:
#!/usr/bin/env bash
cd /var/log
LOG_LEVEL=debug
echo "inside the script: PWD=$PWD LOG_LEVEL=$LOG_LEVEL"Run it each way and check what is left behind in the calling shell:
pwd
./setenv.sh
echo "after ./setenv.sh: PWD=$PWD LOG_LEVEL=$LOG_LEVEL"
source setenv.sh
echo "after source: PWD=$PWD LOG_LEVEL=$LOG_LEVEL"/home/sid/a1
inside the script: PWD=/var/log LOG_LEVEL=debug
after ./setenv.sh: PWD=/home/sid/a1 LOG_LEVEL=
inside the script: PWD=/var/log LOG_LEVEL=debug
after source: PWD=/var/log LOG_LEVEL=debugA child process gets a copy of your environment, and its changes die with it. That is why a script can never cd for you. Sourcing runs the lines in your own shell, so the cd and the variable stick. That is exactly what you want for ~/.bashrc, a Python virtualenv's activate file, or a file of shared settings, and exactly what you don't want for a normal script.
The sharpest edge is exit. In a child process it ends the script. In a sourced file it ends the shell that sourced it:
cat stop.sh
bash -c './stop.sh; echo "caller still running, stop.sh returned $?"'
bash -c 'source ./stop.sh; echo "this line never runs"'#!/usr/bin/env bash
echo "stop.sh: something is wrong, exiting"
exit 1
stop.sh: something is wrong, exiting
caller still running, stop.sh returned 1
stop.sh: something is wrong, exitingI used bash -c so the sourced exit killed a throwaway shell instead of my terminal. Typed directly at your prompt, source ./stop.sh closes the terminal window. Files meant to be sourced should never call exit.
Positional parameters
Arguments you pass to a script arrive in numbered variables. This script prints them:
#!/usr/bin/env bash
echo "Script name: $0"
echo "First: $1"
echo "Second: $2"
echo "Third: $3"
echo "Count: $#"./show-args.sh web01 "error log" 30
./show-args.shScript name: ./show-args.sh
First: web01
Second: error log
Third: 30
Count: 3
Script name: ./show-args.sh
First:
Second:
Third:
Count: 0The quotes around "error log" made it one argument; the shell removed them before the script saw anything. Missing arguments are simply empty, with no error, which is why scripts must check $# themselves.
| Parameter | Meaning |
|---|---|
$0 | the name the script was called by (./show-args.sh) |
$1 … $9 | the first nine arguments |
${10}, ${11} … | argument ten onward; the braces are required |
$# | how many arguments there are |
"$@" | all arguments, each one kept as a separate word |
"$*" | all arguments joined into one string |
The braces for two-digit positions are not optional. $10 means $1 followed by a literal 0:
set -- a b c d e f g h i j k
echo "$10 versus ${10}"a0 versus j(set -- replaces the current positional parameters, a handy way to experiment at the prompt.)
Optional arguments usually get a default with the ${2:-7} expansion from the variables article: "use $2, or 7 if it is unset or empty". We'll use it for the number of days in archive-logs.sh.
"$@" versus "$*" (and why it matters)
These look interchangeable until an argument contains a space. printf repeats its format once per argument, which makes the difference visible:
#!/usr/bin/env bash
echo '"$@" gives:'
printf ' [%s]\n' "$@"
echo '"$*" gives:'
printf ' [%s]\n' "$*"
echo '$@ unquoted gives:'
printf ' [%s]\n' $@./quoting.sh "app 2026-11-01.log" error.log"$@" gives:
[app 2026-11-01.log]
[error.log]
"$*" gives:
[app 2026-11-01.log error.log]
$@ unquoted gives:
[app]
[2026-11-01.log]
[error.log]Only "$@" preserves what the caller passed. Here is the bug that shows up in real wrapper scripts:
#!/usr/bin/env bash
# logsize.sh - show how much disk space the given log files use
du -h $*ls logs
./logsize.sh "logs/app 2026-11-01.log" logs/error.log'app 2026-11-01.log' error.log
du: cannot access 'logs/app': No such file or directory
du: cannot access '2026-11-01.log': No such file or directory
104K logs/error.logChange the last line to du -h "$@" and the same call works:
4.0K logs/app 2026-11-01.log
104K logs/error.logThe rule: whenever a script passes its arguments on to another command, write "$@", with the quotes.
shift
shift drops $1 and moves every other argument down one place: $2 becomes $1, $# goes down by one. It's how you peel off a leading argument and pass the rest along:
#!/usr/bin/env bash
env_name=$1
shift
echo "Environment: $env_name"
echo "Remaining: $# argument(s)"
printf ' service: %s\n' "$@"./deploy-args.sh staging api worker schedulerEnvironment: staging
Remaining: 3 argument(s)
service: api
service: worker
service: schedulershift 2 drops two at once. If you try to shift more arguments than exist, nothing moves and shift returns a failure status:
set -- only-one
shift 2
echo "shift returned $?, still $# argument(s): $1"shift returned 1, still 1 argument(s): only-oneExit codes
Every command finishes with an exit status, a number from 0 to 255. Zero means success; anything else means some kind of failure, and the specific number is up to the program.
true; echo $?
false; echo $?
grep -q '^root:' /etc/passwd; echo $?
grep -q '^nosuchuser:' /etc/passwd; echo $?
ls /nonexistent; echo $?
nosuchcommand; echo $?
chmod -x today.sh; ./today.sh; echo $?0
1
0
1
ls: cannot access '/nonexistent': No such file or directory
2
bash: nosuchcommand: command not found
127
bash: ./today.sh: Permission denied
126grep uses 1 for "no match" (a normal answer, not an error) and reserves 2 for real problems. ls uses 2 for "serious trouble". The shell itself has a few fixed meanings:
| Code | Meaning |
|---|---|
| 0 | success |
| 1 | general failure |
| 2 | misuse: bad arguments or options (Bash builtins and many tools follow this) |
| 126 | the file exists but could not be executed (permissions) |
| 127 | command not found |
| 128 + N | killed by signal N: 130 is Ctrl-C (SIGINT), 137 is kill -9, 143 is SIGTERM |
$? holds the status of the most recent command only, so read it immediately or save it:
ls /nonexistent
echo "ls returned $?"
echo "and now \$? is $?"ls: cannot access '/nonexistent': No such file or directory
ls returned 2
and now $? is 0The second echo reports the status of the first echo, which succeeded.
exit: choosing your script's status
A script's exit status is the status of the last command it ran, unless you end it with exit N. The value is truncated to 8 bits, which produces some surprises:
cat exit-demo.sh
./exit-demo.sh 3; echo "exit status: $?"
./exit-demo.sh 256; echo "exit status: $?"
./exit-demo.sh 300; echo "exit status: $?"
./exit-demo.sh -1; echo "exit status: $?"#!/usr/bin/env bash
echo "about to exit with $1"
exit "$1"
about to exit with 3
exit status: 3
about to exit with 256
exit status: 0
about to exit with 300
exit status: 44
about to exit with -1
exit status: 255exit 256 reports success. Never compute an exit status from a count (exit $errors), because 256 errors would look like none. Pick a small fixed set of codes and document them at the top of the script. The convention I use, and the one archive-logs.sh follows: 0 for success, 1 for "tried and failed", 2 for "you called me wrong".
Exit codes are how scripts talk to everything else. && and || read them, if reads them, cron and systemd log them, and CI systems fail a build step on any non-zero status.
Testing conditions: test, [ ] and [[ ]]
if doesn't evaluate expressions. It runs a command and checks its exit status. To compare strings or check files you run a command whose whole job is to return 0 or 1, and that command is test, better known by its other name [:
type test [ [[
ls -l /usr/bin/[test is a shell builtin
[ is a shell builtin
[[ is a shell keyword
-rwxr-xr-x 1 root root 55744 Aug 25 11:09 '/usr/bin/['[ is a command (there is even a standalone program called [), and ] is just its required last argument. That explains the most common beginner errors: every piece must be a separate word, separated by spaces.
#!/usr/bin/env bash
file=report.csv
if [-f "$file" ]; then echo "found $file"; fi
if [ -f "$file"]; then echo "found $file"; fi./brackets.sh: line 3: [-f: command not found
./brackets.sh: line 4: [: missing `]'On line 3, Bash looked for a command named [-f. On line 4, the last argument was report.csv], not ].
Quote everything inside [ ]
Because [ is an ordinary command, its arguments go through word splitting like any other. An empty or multi-word variable changes the number of arguments it receives:
#!/usr/bin/env bash
role=$1
if [ $role = admin ]; then
echo "full access"
else
echo "read-only access"
fi./role.sh admin
./role.sh
./role.sh "super admin"full access
./role.sh: line 3: [: =: unary operator expected
read-only access
./role.sh: line 3: [: too many arguments
read-only accessWith no argument, [ $role = admin ] became [ = admin ]. With super admin it became [ super admin = admin ]. Writing [ "$role" = admin ] fixes both.
[[ ]]: the Bash version
[[ ]] is a keyword, not a command, so Bash parses it specially: variables inside it are not word-split, and it adds pattern and regex matching. The same script with [[ $role == admin ]] and no quotes behaves correctly:
read-only access
read-only access
full access(Those are the runs with no argument, "super admin" and admin.) In Bash scripts I use [[ ]] everywhere and keep [ ] for scripts that must run under sh.
String and number tests
| Test | True when |
|---|---|
-z "$s" | $s is empty |
-n "$s" | $s is not empty |
"$a" = "$b" | strings are equal (== also works in Bash) |
"$a" != "$b" | strings differ |
$a -eq $b | integers are equal (-ne not equal) |
$a -lt $b | less than (-le less or equal) |
$a -gt $b | greater than (-ge greater or equal) |
name=""
[ -z "$name" ] && echo "name is empty"
name="report.csv"
[ -n "$name" ] && echo "name is set to $name"
[ "$name" != "report.txt" ] && echo "not report.txt"name is empty
name is set to report.csv
not report.txtNumbers and strings use different operators, and mixing them up fails in two different ways. [ ] complains loudly when a "number" isn't one, but [[ ]] evaluates the operands as arithmetic, where an unknown word counts as a variable name with value 0, so it fails silently:
count=abc
[ "$count" -gt 5 ]; echo "status $?"
[[ $count -gt 5 ]]; echo "status $?"bash: [: abc: integer expression expected
status 2
status 1That silent status 1 is why scripts should validate that input is numeric before comparing it (the regex test below does that). The opposite mistake is using > for numbers:
[[ 10 > 9 ]] && echo "10 > 9" || echo "as strings, 10 sorts before 9"
[[ 10 -gt 9 ]] && echo "10 is greater than 9"as strings, 10 sorts before 9
10 is greater than 9Inside [[ ]], < and > compare strings alphabetically. Inside [ ] they are worse: they are redirections. In an empty directory:
a=apple; b=banana
[ "$a" > "$b" ] && echo "apple sorts after banana?"
ls -lapple sorts after banana?
total 0
-rw-r--r-- 1 sid sid 0 Nov 9 21:26 bananaThat ran [ "apple" ] (true, the string is non-empty) with its output redirected into a new file called banana. Use -gt/-lt for numbers, or the arithmetic (( )) syntax covered in Arrays, Associative Arrays, and Arithmetic.
File tests
| Test | True when the path… |
|---|---|
-e | exists (any type) |
-f | is a regular file (following symlinks) |
-d | is a directory |
-L | is a symbolic link |
-r / -w / -x | is readable / writable / executable by you |
-s | exists and is not empty |
a -nt b | a is newer than b (-ot for older) |
ls -l
[ -e old.log ] && echo "old.log exists"
[ -f /etc ] || echo "/etc is not a regular file"
[ -d /etc ] && echo "/etc is a directory"
[ -r /etc/shadow ] || echo "cannot read /etc/shadow"
[ -x /usr/bin/tar ] && echo "tar is executable"
[ -s empty.log ] || echo "empty.log is empty"
[ new.log -nt old.log ] && echo "new.log is newer than old.log"
[ -L current.log ] && echo "current.log is a symlink"
[ -f current.log ] && echo "current.log is also a regular file (-f follows the link)"total 8
lrwxrwxrwx 1 sid sid 7 Nov 9 21:25 current.log -> new.log
-rw-r--r-- 1 sid sid 0 Nov 9 21:25 empty.log
-rw-r--r-- 1 sid sid 2 Nov 9 21:25 new.log
-rw-r--r-- 1 sid sid 2 Nov 7 21:25 old.log
old.log exists
/etc is not a regular file
/etc is a directory
cannot read /etc/shadow
tar is executable
empty.log is empty
new.log is newer than old.log
current.log is a symlink
current.log is also a regular file (-f follows the link)The last line catches people out: -f and -d look through symlinks, so test -L first if you need to know about the link itself.
Patterns and regular expressions with [[ ]]
On the right of ==, [[ ]] treats an unquoted string as a glob pattern, the same *, ? and […] you use for filenames (see Wildcards, Globbing, and Brace Expansion). Quoting it makes it literal:
file="nginx-access.log.2"
[[ $file == *.log ]] && echo "ends in .log" || echo "does not end in .log"
[[ $file == *.log* ]] && echo "matches *.log*"
[[ $file == "*.log*" ]] && echo "literal match" || echo "quoted pattern is compared literally"
branch="release/2.4"
[[ $branch == release/* ]] && echo "release branch"does not end in .log
matches *.log*
quoted pattern is compared literally
release branchFor anything a glob can't express, =~ matches an extended regular expression. Parenthesised groups land in BASH_REMATCH, an array (arrays get their own article; for now ${BASH_REMATCH[1]} is "the first group"):
version="v2.14.3"
[[ $version =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] && echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]} patch=${BASH_REMATCH[3]}"
[[ $version =~ "^v[0-9]+" ]] && echo "match" || echo "no match: quoted regex is literal text"major=2 minor=14 patch=3
no match: quoted regex is literal textQuoting the regex has the same effect as quoting a glob: it turns into a literal string. Long regexes are easier to read (and to get right) stored in a variable, used unquoted:
semver='^v([0-9]+)\.([0-9]+)\.([0-9]+)$'
[[ v3.0.1 =~ $semver ]] && echo "major version ${BASH_REMATCH[1]}"
[[ 3.0 =~ $semver ]] || echo "3.0 is not a valid version tag"major version 3
3.0 is not a valid version tagCombining tests
Inside [[ ]] you can use &&, ||, ! and parentheses. With [ ], combine separate tests using the shell's own && and || (the old -a and -o operators inside [ ] are ambiguous and deprecated):
f=/etc/hostname
[[ -f $f && -r $f ]] && echo "$f is a readable file"
[ -f "$f" ] && [ -r "$f" ] && echo "same test with [ ]"
[[ ! -d $f ]] && echo "$f is not a directory"/etc/hostname is a readable file
same test with [ ]
/etc/hostname is not a directory[ ] / test | [[ ]] | |
|---|---|---|
Works in sh | yes | no (Bash, Zsh, Ksh) |
| Word splitting of variables | yes, so quote everything | no |
Glob patterns with == | no | yes |
Regex with =~ | no | yes |
&&, || inside | no | yes |
< and > | redirections (a bug) | string comparison |
if, elif and else
The full shape is:
if COMMAND; then
…
elif OTHER_COMMAND; then
…
else
…
fiAny command can be the condition, not just tests. grep -q (quiet: exit status only) and command -v (is this program installed?) are two you'll use constantly:
if grep -q 'ERROR' logs/error.log; then echo "errors found: $(grep -c 'ERROR' logs/error.log)"; fi
if ! command -v jq >/dev/null; then echo "jq is missing"; else echo "jq is at $(command -v jq)"; fierrors found: 2000
jq is at /usr/bin/jq! inverts the status of the command after it. An elif chain checks conditions in order and runs only the first branch that matches. This disk check reports in the format monitoring systems like Nagios expect, where exit 0 is OK, 1 is WARNING and 2 is CRITICAL; the thresholds can be overridden with environment variables:
#!/usr/bin/env bash
# disk-check.sh - report how full a filesystem is (Nagios-style exit codes)
mount=${1:-/}
warn_at=${WARN_AT:-75}
crit_at=${CRIT_AT:-90}
usage=$(df --output=pcent "$mount" | tail -n 1 | tr -dc '0-9')
if [ "$usage" -ge "$crit_at" ]; then
echo "CRITICAL: $mount is ${usage}% full"
exit 2
elif [ "$usage" -ge "$warn_at" ]; then
echo "WARNING: $mount is ${usage}% full"
exit 1
else
echo "OK: $mount is ${usage}% full"
fiMy lab disk is nearly empty, so I lowered the thresholds to exercise every branch:
./disk-check.sh /; echo "exit $?"
WARN_AT=1 ./disk-check.sh /; echo "exit $?"
WARN_AT=1 CRIT_AT=1 ./disk-check.sh /; echo "exit $?"OK: / is 1% full
exit 0
WARNING: / is 1% full
exit 1
CRITICAL: / is 1% full
exit 2tr -dc '0-9' deletes every character that isn't a digit, turning " 1%" into 1 so that -ge gets a clean integer. Note the order of the branches: the critical check must come first, because a disk at 95% also passes the warning test.
case: matching one value against patterns
When you're comparing one value against several possibilities, case is clearer than a stack of elifs. Each branch is a glob pattern, | separates alternatives, ;; ends a branch, and *) catches everything else:
#!/usr/bin/env bash
# svc.sh - one front door for a service's lifecycle commands
case $1 in
start|stop|restart)
echo "would run: systemctl $1 myapp.service"
;;
status|"")
echo "would run: systemctl status myapp.service"
;;
-h|--help)
echo "Usage: svc.sh {start|stop|restart|status}"
;;
*)
echo "svc.sh: unknown command '$1'" >&2
echo "Usage: svc.sh {start|stop|restart|status}" >&2
exit 2
;;
esac./svc.sh restart
./svc.sh
./svc.sh reload; echo "exit $?"would run: systemctl restart myapp.service
would run: systemctl status myapp.service
svc.sh: unknown command 'reload'
Usage: svc.sh {start|stop|restart|status}
exit 2"" matches an empty value, so running the script with no argument means "status". Patterns are globs, so case is also good at classifying names. Branches are tried top to bottom and the first match wins, which is why *.tar.gz must come before *.gz:
#!/usr/bin/env bash
# classify.sh - say what kind of file a name looks like
case $1 in
*.tar.gz|*.tgz) echo "$1: compressed tarball" ;;
*.gz) echo "$1: gzip-compressed file" ;;
*.log|*.log.[0-9]) echo "$1: active or rotated log" ;;
[0-9][0-9][0-9][0-9]-*) echo "$1: name starts with a year" ;;
*) echo "$1: unknown" ;;
esac./classify.sh backup-2026-11-09.tar.gz
./classify.sh access.log.gz
./classify.sh nginx.log.3
./classify.sh 2026-11-09-report.csv
./classify.sh notes.txtbackup-2026-11-09.tar.gz: compressed tarball
access.log.gz: gzip-compressed file
nginx.log.3: active or rotated log
2026-11-09-report.csv: name starts with a year
notes.txt: unknownBash also has ;& (fall through into the next branch) and ;;& (keep testing the remaining patterns) as branch terminators. They're rare enough that a reader will have to look them up, so I avoid them; see the GNU Bash manual on conditional constructs if you meet one.
Putting it together: archive-logs.sh
Here is the tool from the start of the article. It takes an optional -n/--dry-run flag, a log directory, and an optional age in days, then moves every .log file older than that into a dated tarball:
#!/usr/bin/env bash
# archive-logs.sh - move .log files older than DAYS days into a dated tarball
#
# Exit codes: 0 = success or nothing to do, 1 = runtime error, 2 = usage error
usage="Usage: archive-logs.sh [-n|--dry-run] LOG_DIR [DAYS]"
dry_run=no
# 1. Options come first.
case $1 in
-h|--help)
echo "$usage"
echo "Archive *.log files older than DAYS days (default 7) into LOG_DIR/archive."
exit 0
;;
-n|--dry-run)
dry_run=yes
shift
;;
-*)
echo "archive-logs.sh: unknown option '$1'" >&2
echo "$usage" >&2
exit 2
;;
esac
# 2. Then the positional arguments.
if [[ $# -lt 1 || $# -gt 2 ]]; then
echo "$usage" >&2
exit 2
fi
log_dir=$1
days=${2:-7}
if [[ ! -d $log_dir ]]; then
echo "archive-logs.sh: '$log_dir' is not a directory" >&2
exit 1
fi
if [[ ! $days =~ ^[0-9]+$ ]]; then
echo "archive-logs.sh: DAYS must be a whole number, got '$days'" >&2
exit 2
fi
# 3. Find the candidates (names only, one per line, sorted).
old_logs=$(find "$log_dir" -maxdepth 1 -type f -name '*.log' -mtime +"$days" -printf '%f\n' | sort)
if [[ -z $old_logs ]]; then
echo "Nothing to archive: no .log files older than $days days in $log_dir"
exit 0
fi
archive="$log_dir/archive/logs-$(date +%F).tar.gz"
if [[ -e $archive ]]; then
echo "archive-logs.sh: $archive already exists, refusing to overwrite" >&2
exit 1
fi
count=$(printf '%s\n' "$old_logs" | wc -l)
echo "Archiving $count file(s) to $archive:"
printf '%s\n' "$old_logs" | sed 's/^/ /'
if [[ $dry_run == yes ]]; then
echo "Dry run: nothing was changed."
exit 0
fi
mkdir -p "$log_dir/archive" || exit 1
# 4. tar reads the names from stdin (-T -) and deletes each file once it is safely archived.
if printf '%s\n' "$old_logs" | tar -czf "$archive" -C "$log_dir" -T - --remove-files; then
echo "Done."
else
echo "archive-logs.sh: tar failed, logs left in place" >&2
exit 1
fiThe test directory has logs of various ages, one with a space in its name, and a .txt file that must not be touched:
ls -l myapp-logstotal 96
-rw-r--r-- 1 sid sid 22400 Oct 20 22:27 api-2026-10-20.log
-rw-r--r-- 1 sid sid 21280 Oct 28 22:27 api-2026-10-28.log
-rw-r--r-- 1 sid sid 22960 Nov 5 21:27 api-2026-11-05.log
-rw-r--r-- 1 sid sid 5040 Nov 9 21:27 api-2026-11-09.log
-rw-r--r-- 1 sid sid 2800 Oct 30 22:27 'batch run 2026-10-30.log'
-rw-r--r-- 1 sid sid 168 Oct 10 22:27 notes.txt
-rw-r--r-- 1 sid sid 6720 Oct 25 22:27 worker-2026-10-25.logFirst, every way of calling it wrong:
./archive-logs.sh; echo "exit $?"
./archive-logs.sh --verbose myapp-logs; echo "exit $?"
./archive-logs.sh /var/log/myapp; echo "exit $?"
./archive-logs.sh myapp-logs 1week; echo "exit $?"Usage: archive-logs.sh [-n|--dry-run] LOG_DIR [DAYS]
exit 2
archive-logs.sh: unknown option '--verbose'
Usage: archive-logs.sh [-n|--dry-run] LOG_DIR [DAYS]
exit 2
archive-logs.sh: '/var/log/myapp' is not a directory
exit 1
archive-logs.sh: DAYS must be a whole number, got '1week'
exit 2Then a dry run, the real run, and the result:
./archive-logs.sh --dry-run myapp-logs
./archive-logs.sh myapp-logs; echo "exit $?"
ls myapp-logs myapp-logs/archive
tar -tzf myapp-logs/archive/logs-2026-11-09.tar.gzArchiving 4 file(s) to myapp-logs/archive/logs-2026-11-09.tar.gz:
api-2026-10-20.log
api-2026-10-28.log
batch run 2026-10-30.log
worker-2026-10-25.log
Dry run: nothing was changed.
Archiving 4 file(s) to myapp-logs/archive/logs-2026-11-09.tar.gz:
api-2026-10-20.log
api-2026-10-28.log
batch run 2026-10-30.log
worker-2026-10-25.log
Done.
exit 0
myapp-logs:
api-2026-11-05.log api-2026-11-09.log archive notes.txt
myapp-logs/archive:
logs-2026-11-09.tar.gz
api-2026-10-20.log
api-2026-10-28.log
batch run 2026-10-30.log
worker-2026-10-25.logRunning it again is safe, and a second run on the same day with a shorter window refuses to clobber the archive:
./archive-logs.sh myapp-logs; echo "exit $?"
./archive-logs.sh myapp-logs 3; echo "exit $?"Nothing to archive: no .log files older than 7 days in myapp-logs
exit 0
archive-logs.sh: myapp-logs/archive/logs-2026-11-09.tar.gz already exists, refusing to overwrite
exit 1The design choices are the point of this article, more than the specific commands:
- Options are handled first, with
case, then removed withshift. After that,$1and$2mean the same thing whether or not--dry-runwas given. - Everything is validated before anything is changed. The directory exists, the day count is a number, the archive doesn't already exist. Only then does
tarrun. - Errors go to stderr (
>&2) and carry the script's name, so they show up in cron mail and logs even when stdout is redirected, and you can tell which script complained. - The exit codes are documented at the top and mean one thing each. "Nothing to archive" is success, not failure: the job did what it was asked.
--remove-filesdeletes each log only after tar has archived it, so a failure halfway through leaves the remaining logs in place.
One find detail: -mtime +7 means "more than 7 whole 24-hour periods ago", so a file needs to be at least 8 days old to match. That is usually what people want from "older than 7 days", but check it against your retention policy. Finding Files with find, locate, and xargs covers -mtime in detail.
Where you'll use this
Almost every script you'll write for work is one of these shapes:
- Scheduled jobs. cron and systemd timers run scripts unattended, so the only feedback is the exit status and stderr. A cleanup job like
archive-logs.shis a typical example; scheduling it is covered in System Monitoring and Scheduling with cron and systemd. - CI and deployment steps. Jenkins, GitHub Actions and every other CI system run shell steps and fail the build on a non-zero exit. A step that prints "ERROR" but exits 0 is a passing step. See Your First Pipeline: Jenkinsfile Basics.
- Monitoring checks.
disk-check.shabove follows the Nagios plugin contract (0/1/2), which many monitoring agents can run directly. - Wrappers. Small front doors like
svc.shthat give a team one memorable command instead of five long ones. - Git hooks. Git runs scripts in
.git/hooks/at fixed points, and a non-zero exit frompre-commitaborts the commit.
That last one is a complete, practical use of everything in this article. This hook refuses commits straight to main or a release/ branch, and refuses any staged change containing a DO NOT COMMIT marker:
#!/usr/bin/env bash
# pre-commit - refuse commits that are obviously not ready
# git runs this before every commit; a non-zero exit aborts the commit.
branch=$(git symbolic-ref --short HEAD)
if [[ $branch == main || $branch == release/* ]]; then
echo "pre-commit: don't commit directly to '$branch'; use a feature branch" >&2
exit 1
fi
if git diff --cached | grep -q '^+.*DO NOT COMMIT'; then
echo "pre-commit: staged changes contain a DO NOT COMMIT marker:" >&2
git --no-pager diff --cached --name-only -G 'DO NOT COMMIT' >&2
exit 1
fi
exit 0Saved as .git/hooks/pre-commit in a test repository:
chmod +x .git/hooks/pre-commit
echo 'timeout_seconds = 30' > config.ini
git add config.ini
git commit -m "Add config"
git switch -c feature/timeouts
echo 'debug_password = hunter2 # DO NOT COMMIT' >> config.ini
git add config.ini
git commit -m "Add config"
sed -i '/DO NOT COMMIT/d' config.ini
git add config.ini
git commit -m "Add config"pre-commit: don't commit directly to 'main'; use a feature branch
Switched to a new branch 'feature/timeouts'
pre-commit: staged changes contain a DO NOT COMMIT marker:
config.ini
[feature/timeouts 015c879] Add config
1 file changed, 1 insertion(+)
create mode 100644 config.iniThe --no-pager is there because of a real bug in my first version: with the output going to the terminal, git diff opened a pager in the middle of the commit and sat waiting for a keypress. grep '^+.*DO NOT COMMIT' only looks at added lines (+), so removing an old marker doesn't trip the hook.
Common mistakes
Windows line endings: bash\r: No such file or directory
A script edited on Windows (or checked out by Git with autocrlf) has CRLF line endings. The kernel then reads the shebang as bash followed by an invisible carriage return:
./crlf.sh
file crlf.sh
cat -A crlf.sh/usr/bin/env: ‘bash\r’: No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines
crlf.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
#!/usr/bin/env bash^M$
echo "Backup starting"^M$cat -A shows the carriage returns as ^M. Strip them and the script runs:
sed -i 's/\r$//' crlf.sh
./crlf.shBackup startingdos2unix does the same if it is installed. To stop it happening again, set your editor to LF line endings for shell scripts, or add *.sh text eol=lf to the repository's .gitattributes.
Spaces around = in an assignment
#!/usr/bin/env bash
days = 7
echo "keeping $days days of logs"./spaces.sh: line 2: days: command not found
keeping days of logsWith spaces, Bash reads days = 7 as "run the command days with arguments = and 7". The script then carries on with $days empty. Assignments are written days=7, no spaces. (Tests are the opposite: [ "$a" = "$b" ] needs the spaces.)
A missing fi (or done, or esac)
#!/usr/bin/env bash
if [[ -d /var/log ]]; then
echo "log directory present"./nofi.sh: line 4: syntax error: unexpected end of fileBash reached the end of the file still waiting for fi. The line number points to the end of the file, not to the if that wasn't closed, so look upward for the opening keyword. bash -n script.sh checks syntax without running anything; we use it more in Error Handling, Traps, and Debugging.
Unquoted variables and missing spaces in [ ]
Covered above, but they are common enough to repeat: [: =: unary operator expected and [: too many arguments mean a variable inside [ ] was empty or contained spaces. Quote it or switch to [[ ]]. [-f: command not found and [: missing `]' mean a space is missing next to a bracket.
Summary
- Start every Bash script with
#!/usr/bin/env bash. A#!/bin/shscript runs underdashon Debian and Ubuntu, where[[ ]]and other Bash features don't exist. ./script.shandbash script.shrun in a child process, so theircdand variables vanish when they finish.sourceruns the file in your current shell, where anexitcloses your shell.- Arguments arrive as
$1,$2, … (${10}needs braces),$#counts them, and"$@"passes them on intact.$*and unquoted$@break arguments that contain spaces. - Exit status 0 means success. Use a small documented set of codes (0 success, 1 failure, 2 usage), send error messages to stderr, and never
exitwith a computed number: 256 wraps to 0. [is a command, so it needs spaces around every part and quotes around every variable.[[ ]]doesn't word-split and adds glob matching with==and regex matching with=~(groups inBASH_REMATCH); quoting the pattern makes it literal.- Use
-eq,-lt,-gtfor numbers.>inside[[ ]]compares strings, and inside[ ]it creates a file. ifruns any command and branches on its exit status.casematches one value against glob patterns, first match wins, so put specific patterns before general ones.- Validate every argument before the script changes anything, and handle options first with
caseandshift.
Exercises
Write greet.sh NAME [GREETING]. With one argument it prints Hello, NAME!; with two it uses the given greeting. With no arguments or more than two, it prints a usage line to stderr and exits with status 2.
Show Solution
#!/usr/bin/env bash
# greet.sh - greet someone by name
if [[ $# -lt 1 || $# -gt 2 ]]; then
echo "Usage: greet.sh NAME [GREETING]" >&2
exit 2
fi
name=$1
greeting=${2:-Hello}
echo "$greeting, $name!"./greet.sh; echo "exit $?"
./greet.sh Priya
./greet.sh Priya "Good morning"Usage: greet.sh NAME [GREETING]
exit 2
Hello, Priya!
Good morning, Priya!${2:-Hello} supplies the default, and checking $# up front means the rest of the script can trust $1.
Write is-weekend.sh [DATE] that exits 0 if the date (default: today) is a Saturday or Sunday and 1 otherwise, printing nothing, so it can be used as ./is-weekend.sh && echo weekend. If the date is invalid, exit 2. Use case.
Hint
date -d "$1" +%u prints the day of the week as a number, 1 for Monday through 7 for Sunday.
Show Solution
#!/usr/bin/env bash
# is-weekend.sh [DATE] - exit 0 on Saturday or Sunday, 1 otherwise
day=$(date -d "${1:-today}" +%u) || exit 2
case $day in
6|7) exit 0 ;;
*) exit 1 ;;
esacdate -d 2026-11-08 +%A
./is-weekend.sh 2026-11-08 && echo "weekend"
./is-weekend.sh 2026-11-10 || echo "weekday"
./is-weekend.sh yesterday-ish; echo "exit $?"Sunday
weekend
weekday
date: invalid date ‘yesterday-ish’
exit 2The assignment day=$(…) takes the exit status of the command substitution, so || exit 2 fires when date rejects the input. A script whose whole output is its exit status is a perfectly good building block: a cron job can start with ./is-weekend.sh && exit 0 to skip weekends.
Write check-port.sh PORT. It must reject a missing argument, anything that isn't a whole number, and numbers outside 1–65535 (exit 2 with a message on stderr). For valid ports below 1024, print that binding to the port needs root; otherwise print that the port is valid.
Show Solution
#!/usr/bin/env bash
# check-port.sh PORT - validate a TCP port number
if [[ $# -ne 1 ]]; then
echo "Usage: check-port.sh PORT" >&2
exit 2
fi
port=$1
if [[ ! $port =~ ^[0-9]+$ ]]; then
echo "check-port.sh: '$port' is not a number" >&2
exit 2
elif [[ $port -lt 1 || $port -gt 65535 ]]; then
echo "check-port.sh: $port is out of range (1-65535)" >&2
exit 2
elif [[ $port -lt 1024 ]]; then
echo "$port is valid, but binding to it needs root"
else
echo "$port is valid"
fi./check-port.sh 8080
./check-port.sh 443
./check-port.sh 70000; echo "exit $?"
./check-port.sh http; echo "exit $?"
./check-port.sh; echo "exit $?"8080 is valid
443 is valid, but binding to it needs root
check-port.sh: 70000 is out of range (1-65535)
exit 2
check-port.sh: 'http' is not a number
exit 2
Usage: check-port.sh PORT
exit 2The regex check has to come first. Without it, http would reach [[ $port -lt 1 ]], be evaluated as an unset variable (0), and produce a misleading "out of range" message.
Write backup-config.sh [-f|--force] FILE [DEST_DIR] that copies FILE to DEST_DIR/FILE.YYYY-MM-DD.bak (DEST_DIR defaults to backups, created if missing). If today's backup already exists, refuse with exit 1 unless --force was given. Unknown options and wrong argument counts exit 2; an unreadable FILE exits 1.
Show Solution
#!/usr/bin/env bash
# backup-config.sh [-f|--force] FILE [DEST_DIR]
# Copy FILE to DEST_DIR/FILE.YYYY-MM-DD.bak (DEST_DIR defaults to ./backups).
usage="Usage: backup-config.sh [-f|--force] FILE [DEST_DIR]"
force=no
case $1 in
-f|--force) force=yes; shift ;;
-h|--help) echo "$usage"; exit 0 ;;
-*) echo "backup-config.sh: unknown option '$1'" >&2; echo "$usage" >&2; exit 2 ;;
esac
if [[ $# -lt 1 || $# -gt 2 ]]; then
echo "$usage" >&2
exit 2
fi
src=$1
dest_dir=${2:-backups}
if [[ ! -f $src || ! -r $src ]]; then
echo "backup-config.sh: cannot read '$src'" >&2
exit 1
fi
target="$dest_dir/$(basename "$src").$(date +%F).bak"
if [[ -e $target && $force == no ]]; then
echo "backup-config.sh: $target exists (use --force to overwrite)" >&2
exit 1
fi
mkdir -p "$dest_dir" || exit 1
cp "$src" "$target" || exit 1
echo "Backed up $src to $target"./backup-config.sh app.conf
./backup-config.sh app.conf; echo "exit $?"
./backup-config.sh --force app.conf
./backup-config.sh -x app.conf; echo "exit $?"
./backup-config.sh nope.conf /tmp; echo "exit $?"
ls backupsBacked up app.conf to backups/app.conf.2026-11-09.bak
backup-config.sh: backups/app.conf.2026-11-09.bak exists (use --force to overwrite)
exit 1
Backed up app.conf to backups/app.conf.2026-11-09.bak
backup-config.sh: unknown option '-x'
Usage: backup-config.sh [-f|--force] FILE [DEST_DIR]
exit 2
backup-config.sh: cannot read 'nope.conf'
exit 1
app.conf.2026-11-09.bakThis has the same skeleton as archive-logs.sh: options via case and shift, argument count, validation, a refuse-to-clobber check, and only then the action. With more than one option, a single case stops being enough; that's what loops (next article) and getopts (in Writing Production-Ready Scripts) are for.
Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026. Every script and command above was run as shown, the interactive examples in a real terminal session, and the outputs are pasted unedited. The surprise while testing was the pre-commit hook: my first version let git diff open a pager mid-commit, hence --no-pager. The hook was tested in a throwaway Git repository; the macOS remark about /bin/bash being version 3.2 comes from Apple's shipped Bash and was not re-checked on a Mac. Paths from the test machine's scratch directories are shown shortened to /home/sid/….
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.