Scheduling Bash Scripts with cron

Su Suriya Ravichandran Updated 06 Dec 2026
18 min read ·Lesson 170 of 205

Most of the automation scripts in this part of the tutorial, such as backups, log rotation, disk and load checks, website checks and updates, are only useful if they run regularly without anyone starting them. On Linux and other Unix-like systems, the classic tool for that is cron: a background service (a daemon) that wakes up every minute, reads a set of schedule tables called crontabs, and runs every command whose schedule matches the current minute.

cron is simple and almost universal, but it runs scripts in a very different situation from an interactive terminal: with almost no environment variables, without a terminal, from a different folder, with a different shell, and with nobody watching the output. Nearly every "it works when I run it, but not from cron" problem comes from these differences. This lesson explains the crontab format, those differences, how to see what cron did, the systemd timer alternative, and then builds a wrapper script that makes any job safe to run from cron.

Understanding the Crontab Format

Each user can have a personal crontab, edited with the crontab command:

CommandEffect
crontab -eedit your crontab in an editor; it is checked and installed when you save
crontab -llist your crontab
crontab -rremove your whole crontab, without asking on most systems
crontab FILEreplace your crontab with the contents of FILE
sudo crontab -u alice -eedit another user's crontab (root only)

Because -r is right next to -e on the keyboard and deletes everything, it is worth keeping a copy: crontab -l > ~/crontab.backup.

Each line of a crontab is either a comment (#), a variable assignment, or a schedule followed by a command. A schedule has five time fields:

# ┌───────────── minute        (0-59)
# │ ┌─────────── hour          (0-23)
# │ │ ┌───────── day of month  (1-31)
# │ │ │ ┌─────── month         (1-12 or jan-dec)
# │ │ │ │ ┌───── day of week   (0-7 or sun-sat; 0 and 7 are both Sunday)
# │ │ │ │ │
  30 2 * * * /usr/local/bin/backup.sh

This line runs backup.sh at 02:30 every day. Each field can contain:

FormExampleMeaning
** in the hour fieldevery value
number30exactly that value
list1,15each listed value
range1-5every value from 1 to 5
step*/15every 15th value, starting at the first (0, 15, 30, 45 for minutes)
range with step9-17/29, 11, 13, 15, 17
namemon-fri, jannames for days and months (not in lists or ranges in all versions)

Some typical schedules:

ScheduleWhen it runs
*/5 * * * *every 5 minutes
0 * * * *at the start of every hour
30 2 * * *every day at 02:30
0 8 * * 1-5Monday to Friday at 08:00
0 3 * * 0every Sunday at 03:00
0 0 1 * *at midnight on the first day of every month
15 0,12 * * *at 00:15 and 12:15

Most cron versions also accept shortcuts in place of the five fields: @hourly, @daily (same as 0 0 * * *), @weekly, @monthly, @yearly, and @reboot, which runs the command once when the cron service starts, usually right after the system boots.

The day-of-month and day-of-week trap

When both the day-of-month and the day-of-week fields are restricted (neither is *), cron runs the command when either matches, not when both match. 0 9 13 * 5 therefore runs at 09:00 on every 13th of the month and on every Friday, not only on Friday the 13th. To combine the two conditions, schedule on one and test the other inside the command or script, for example 0 9 * * 5 [ "$(date +\%d)" = 13 ] && /usr/local/bin/job.sh.

The percent sign

In the command part of a crontab line, cron treats % specially: the first % ends the command, and the text after it is sent to the command as standard input, with each further % becoming a newline. A command that works in a terminal, such as tar -czf /backup/site-$(date +%F).tar.gz /srv/site, therefore breaks in a crontab. Escape every percent sign with a backslash (date +\%F), or, better, move the command into a script file, where % has no special meaning.

Other crontab rules

  • Variable assignments such as MAILTO=admin@example.com or PATH=/usr/local/bin:/usr/bin:/bin apply to the lines below them. They are plain text: $HOME or ~ are not expanded in assignment lines.
  • The file must end with a newline. Depending on the cron version, a last line without one is rejected by crontab or silently ignored.
  • Times are in the system's time zone. Some cron implementations, such as cronie (used by Fedora and RHEL), support a CRON_TZ= variable for a different zone; the cron package Debian and Ubuntu install by default does not. When the clocks change for daylight saving time, a job scheduled in the skipped or repeated hour may run zero or two times; schedules between 01:00 and 03:00 are the ones at risk.

System crontabs

Besides the per-user crontabs, there are system-wide ones:

  • /etc/crontab and the files in /etc/cron.d/ use the same format with one extra field, the user to run the command as, between the schedule and the command. Software packages install their jobs in /etc/cron.d/. For example, Debian's e2fsprogs package installs this line:

    10 3 * * * root test -e /run/systemd/system || SERVICE_MODE=1 /sbin/e2scrub_all -A -r

    It runs as root at 03:10 every day, but only does its work when the system was not started by systemd (which would run its own timer for the job instead).

  • The folders /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/ and /etc/cron.monthly/ contain executable scripts, without schedules, that are run one after another by run-parts at the corresponding interval.

run-parts has strict naming rules on Debian and Ubuntu: by default it only runs files whose names consist of letters, digits, underscores and hyphens. A script named report.sh is silently skipped because of the dot, and so is a file without execute permission. A test folder with four files shows it:

ls /srv/t170/parts
run-parts --test /srv/t170/parts
backup
clean-tmp
noexec
report.sh
/srv/t170/parts/backup
/srv/t170/parts/clean-tmp

--test lists what would be run without running it. Only backup and clean-tmp qualify; noexec is not executable and report.sh has a dot. On Debian and Ubuntu, cron applies the same naming rule to files in /etc/cron.d/.

How cron Runs a Command

For each matching line, cron starts the command in a new process with:

  • the shell /bin/sh, unless the crontab sets SHELL=; on Debian and Ubuntu, /bin/sh is Dash, not Bash;
  • a minimal environment: PATH=/usr/bin:/bin, SHELL=/bin/sh, and HOME and LOGNAME from the user's account, plus any variables set in the crontab; nothing from .bashrc or .profile;
  • the user's home folder as the current folder;
  • no terminal: standard input is not connected to a keyboard;
  • output collected by cron: anything the command prints, on standard output or standard error, is sent by mail to the user (or to MAILTO).

The test machine for this lesson had no cron service, so the examples below reproduce cron's environment directly: they run the crontab command through /bin/sh -c from the home folder, with env -i clearing the environment and setting only the variables cron sets:

# cronenv COMMAND_LINE: run a command line the way cron runs a crontab entry
# (in the home folder, through /bin/sh -c, with cron's minimal environment)
cronenv() {
    ( cd /root && env -i SHELL=/bin/sh PATH=/usr/bin:/bin HOME=/root LOGNAME=root /bin/sh -c "$1" )
}

The script show-env.sh prints its situation:

#!/bin/bash
echo "folder: $PWD"
echo "PATH:   $PATH"
echo "SHELL:  $SHELL"
echo "LANG:   ${LANG-<unset>}"
echo "TERM:   ${TERM-<unset>}"
echo "terminal on stdin: $( [ -t 0 ] && echo yes || echo no )"

Run from an interactive terminal session in /srv/t170/jobs:

folder: /srv/t170/jobs
PATH:   /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
SHELL:  /bin/bash
LANG:   C.UTF-8
TERM:   xterm-256color
terminal on stdin: yes

Run the way cron runs it, with cronenv '/srv/t170/jobs/show-env.sh':

folder: /root
PATH:   /usr/bin:/bin
SHELL:  /bin/sh
LANG:   <unset>
TERM:   dumb
terminal on stdin: no

Every line is different. (TERM=dumb is not set by cron: when TERM is missing, Bash itself sets it to dumb.) Each difference causes a typical failure.

Commands that are not found

/usr/local/bin, where locally installed tools usually live, is not in cron's PATH. purge-cache.sh calls such a tool, sitectl:

#!/bin/bash
sitectl purge
echo "purge finished with status $?"

From the terminal it works; from cron it does not:

$ ./purge-cache.sh
sitectl: cache purged
purge finished with status 0
$ cronenv '/srv/t170/jobs/purge-cache.sh'
/srv/t170/jobs/purge-cache.sh: line 2: sitectl: command not found
purge finished with status 127

The fixes are to set PATH at the top of the crontab or inside the script, or to call tools by their full path (/usr/local/bin/sitectl).

Relative paths

Because the job starts in the home folder, a script that reads config.ini or writes output/report.csv with relative paths uses the wrong folder. Scripts meant for cron should use absolute paths, or change to their own folder first with cd "$(dirname "$0")" || exit 1. The crontab entry itself should also call the script by its absolute path.

Bash syntax in the crontab line

The crontab line is run by /bin/sh, so Bash features in it fail on systems where /bin/sh is Dash:

$ cronenv '[[ -f /etc/hostname ]] && echo found'
/bin/sh: 1: [[: not found

A script with a #!/bin/bash shebang still runs in Bash, because the kernel uses its shebang; only the crontab line itself is interpreted by /bin/sh. Keep crontab lines simple, put the logic in scripts, or set SHELL=/bin/bash in the crontab.

Output and mail

cron mails whatever a job prints. If no mail system is installed, which is common on modern servers, the output is discarded (Debian's cron then logs "No MTA installed, discarding output"). Error messages disappear unnoticed. There are two common approaches:

  • Redirect output to a log file in the crontab line: 30 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1. Note the order: >> file 2>&1 sends both streams to the file (lesson 60).
  • Make jobs print nothing when they succeed and a short report when they fail, and set MAILTO. Then every mail means something needs attention. The complete example below works this way.

Overlapping runs

cron starts a job when its time comes, even if the previous run is still busy. A backup scheduled every hour that one day takes 90 minutes will run twice in parallel, which can corrupt its output or overload the machine. flock -n LOCKFILE COMMAND (lesson 171) skips a run while another holds the lock: 0 * * * * flock -n /run/lock/backup.lock /usr/local/bin/backup.sh.

Checking What cron Did

cron records each command it starts in the system log. On Debian and Ubuntu:

grep CRON /var/log/syslog          # traditional syslog file, where present
journalctl -u cron --since today   # systems that use the systemd journal

On Fedora and RHEL the service is called crond, and the log file is /var/log/cron. These logs show that a command was started, not whether it worked; that is the job's own responsibility, through its exit status, its log file and its messages.

A practical way to test a new entry is to schedule it a couple of minutes ahead, watch it run in the log, and only then change it to the real schedule. To test a script in cron's conditions without waiting, run it with an empty environment, as cronenv does above.

systemd Timers: The Modern Alternative

On systems that use systemd, a timer unit can start a service unit on a schedule. It needs two small files instead of one line, but offers features cron lacks: output goes to the journal automatically, a missed run (because the machine was off) can be caught up with Persistent=true, runs never overlap because a service cannot be started twice, and resources such as CPU and memory can be limited.

# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
# /etc/systemd/system/backup.timer
[Unit]
Description=Run the nightly backup

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target

The timer is activated with systemctl enable --now backup.timer, and systemctl list-timers shows when each timer runs next. (The test machine's systemd was not running as the service manager, so these units were not activated there.) The OnCalendar format is DayOfWeek Year-Month-Day Hour:Minute:Second; systemd-analyze calendar checks an expression and shows its next run times, which is a useful way to test a schedule before relying on it:

systemd-analyze calendar --iterations=2 'Mon..Fri *-*-* 08:00:00'
systemd-analyze calendar --iterations=2 '*:0/15'
Normalized form: Mon..Fri *-*-* 08:00:00
    Next elapse: Wed 2026-11-25 08:00:00 UTC
       From now: 16h left
   Iteration #2: Thu 2026-11-26 08:00:00 UTC
       From now: 1 day 16h left
  Original form: *:0/15
Normalized form: *-*-* *:00/15:00
    Next elapse: Tue 2026-11-24 15:30:00 UTC
       From now: 13min left
   Iteration #2: Tue 2026-11-24 15:45:00 UTC
       From now: 28min left

The first is the systemd form of cron's 0 8 * * 1-5, and the second of */15 * * * *. For a single script on a single server, cron remains perfectly adequate; whichever scheduler is used, the script itself should not depend on the scheduler's environment.

A Complete Example: A Wrapper for cron Jobs

Instead of repeating PATH settings, locks, time limits and log redirections in every crontab line and every script, a small wrapper can provide them for any command. cronjob.sh runs a command with a sensible environment, a lock per job, a time limit and a log file, prints nothing when the job succeeds and a short report when it fails.

#!/usr/bin/env bash
#
# cronjob.sh - run a command from cron with a lock, a time limit and a log
#
# Usage: cronjob.sh [-n NAME] [-t TIMEOUT] [-d LOG_DIR] -- COMMAND [ARG...]
#   -n NAME     job name for the lock and log file (default: the command's name)
#   -t TIMEOUT  stop the command after this long, e.g. 30s, 10m, 2h (default: 1h)
#   -d LOG_DIR  folder for NAME.log (default: /var/log/cronjobs)
#
# Prints nothing when the command succeeds, so cron sends no mail. When it fails
# or times out, prints a short report with the last lines of output, which cron
# mails to MAILTO. Exits with the command's status (124 after a timeout); a run
# skipped because the previous one is still busy exits with 0.

set -uo pipefail

# cron starts jobs with a minimal environment: set what scripts expect
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export LC_ALL=C.UTF-8
umask 027

name='' limit=1h log_dir=/var/log/cronjobs

usage() { echo "usage: ${0##*/} [-n NAME] [-t TIMEOUT] [-d LOG_DIR] -- COMMAND [ARG...]" >&2; exit 2; }
stamp() { printf '%(%Y-%m-%d %H:%M:%S)T' -1; }

while getopts ':n:t:d:' opt; do
    case $opt in
        n) name=$OPTARG ;;
        t) limit=$OPTARG ;;
        d) log_dir=$OPTARG ;;
        *) usage ;;
    esac
done
shift $(( OPTIND - 1 ))
(( $# > 0 )) || usage

[[ -n $name ]] || name=${1##*/}
[[ $name =~ ^[A-Za-z0-9._-]+$ ]] || { echo "${0##*/}: invalid job name: '$name'" >&2; exit 2; }
[[ $limit =~ ^[0-9]+[smhd]?$ ]] || { echo "${0##*/}: invalid timeout: '$limit'" >&2; exit 2; }
mkdir -p -- "$log_dir" || exit 2
log_file=$log_dir/$name.log

# One run per job name: if the previous run is still busy, skip this one
exec 9> "$log_dir/.$name.lock" || exit 2
if ! flock -n 9; then
    echo "$(stamp) [$name] skipped: previous run still active" >> "$log_file"
    exit 0
fi

output=$(mktemp) || exit 2
trap 'rm -f -- "$output"' EXIT

cd / || exit 2                       # never depend on the starting folder
start=$EPOCHSECONDS
echo "$(stamp) [$name] start: $*" >> "$log_file"

timeout --kill-after=30s "$limit" "$@" > "$output" 2>&1 < /dev/null
status=$?

sed "s/^/    /" "$output" >> "$log_file"
echo "$(stamp) [$name] end: status $status after $(( EPOCHSECONDS - start ))s" >> "$log_file"

if (( status != 0 )); then
    case $status in
        124)     reason="timed out after $limit" ;;
        126|127) reason="could not be started (status $status)" ;;
        *)       reason="failed with status $status" ;;
    esac
    logger -t cronjob -p user.err "$name $reason" 2>/dev/null
    echo "Job '$name' on $(hostname) $reason."
    echo "Command: $*"
    echo "Log: $log_file"
    echo "--- last 20 lines of output ---"
    tail -n 20 -- "$output"
fi
exit "$status"

How It Works

  • A known environment. The wrapper sets a full PATH, a UTF-8 locale (LC_ALL=C.UTF-8) so tools behave the same as in a terminal session, and a umask of 027, so files the job creates are not readable by other users. It changes to / so that no job silently depends on starting in the home folder, and it gives the command /dev/null as standard input, so a command that unexpectedly asks a question fails at once instead of hanging.
  • The command as arguments. Everything after -- is the command and its arguments, run as "$@". There is no eval and no extra shell, so arguments with spaces stay intact (lesson 157). The job name defaults to the command's file name and is restricted to safe characters, because it becomes part of file names.
  • No overlaps. Each job name has its own lock file in the log folder, held on file descriptor 9 with flock -n. If the previous run of the same job still holds it, the new run writes a "skipped" line to the log and exits with 0, so that a long run does not also produce error mails every few minutes; the time limit makes sure that no run can hold the lock forever.
  • A time limit. timeout stops the command after the limit with SIGTERM, and --kill-after=30s sends SIGKILL if it is still running 30 seconds later (lesson 142). A timeout gives status 124.
  • A log for every run. The command's output (both streams) goes to a temporary file. After the command ends, the output is appended to NAME.log, indented, between "start" and "end" lines with timestamps, the exit status and the duration. $EPOCHSECONDS, the current time in seconds, requires Bash 5.0 or later. Because the output is added when the job ends, a line written by another run in the meantime (such as a "skipped" line) can appear between the "start" line and the output.
  • Quiet success, useful failure. When the status is 0, the wrapper prints nothing, so cron has nothing to mail. Otherwise it explains what happened (a timeout, a command that could not be started, or an ordinary failure), names the log, and prints the last 20 lines of output, which is usually enough to see the error in the mail itself. It also sends one line to the system log with logger, so failures appear in journalctl or /var/log/syslog even without mail.

Using It in a Crontab

MAILTO=admin@example.com

# m  h  dom mon dow  command
30   2  *   *   *    /usr/local/bin/cronjob.sh -t 2h -- /usr/local/bin/backup.sh
*/5  *  *   *   *    /usr/local/bin/cronjob.sh -n site-check -t 2m -- /usr/local/bin/site-check.sh /etc/site-check/urls.txt
15   0  *   *   *    /usr/local/bin/cronjob.sh -- /usr/local/bin/rotate-logs.sh -k 14 -d 60 /srv/app/logs

Running the Complete Example

The test jobs are small scripts: report.sh prints two lines and succeeds, purge-cache.sh is the script from above that calls sitectl, import.sh prints a message, writes an error to standard error and exits with 3, and slow.sh prints "step 1", sleeps 30 seconds and prints "step 2". Each was run through cronenv, so in exactly the environment cron would give it, with -d /srv/t170/logs for the log folder.

The successful jobs print nothing, which means no mail:

$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -- /srv/t170/jobs/report.sh
[status 0]
$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -- /srv/t170/jobs/purge-cache.sh
[status 0]

purge-cache.sh, which failed with "command not found" in cron's environment earlier, now works because the wrapper sets PATH. Its log shows the output:

2026-11-24 15:15:58 [purge-cache.sh] start: /srv/t170/jobs/purge-cache.sh
    sitectl: cache purged
    purge finished with status 0
2026-11-24 15:15:58 [purge-cache.sh] end: status 0 after 0s

A failing job, a job that runs too long and a command that does not exist each produce a report, which is what cron would mail:

$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -- /srv/t170/jobs/import.sh
Job 'import.sh' on vm failed with status 3.
Command: /srv/t170/jobs/import.sh
Log: /srv/t170/logs/import.sh.log
--- last 20 lines of output ---
importing orders.csv
line 17: bad date '2026-13-01'
[status 3]
$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -t 3s -- /srv/t170/jobs/slow.sh
Job 'slow.sh' on vm timed out after 3s.
Command: /srv/t170/jobs/slow.sh
Log: /srv/t170/logs/slow.sh.log
--- last 20 lines of output ---
step 1
[status 124]
$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -- /srv/t170/jobs/no-such-job.sh
Job 'no-such-job.sh' on vm could not be started (status 127).
Command: /srv/t170/jobs/no-such-job.sh
Log: /srv/t170/logs/no-such-job.sh.log
--- last 20 lines of output ---
timeout: failed to run command ‘/srv/t170/jobs/no-such-job.sh’: No such file or directory
[status 127]

(vm is the host name of the test machine.) The log of the failed import keeps the full output:

2026-11-24 15:15:58 [import.sh] start: /srv/t170/jobs/import.sh
    importing orders.csv
    line 17: bad date '2026-13-01'
2026-11-24 15:15:58 [import.sh] end: status 3 after 0s

To test the lock, a job named nightly was started in the background with slow.sh and a 5-second limit; one second later, a second run of nightly started:

$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -n nightly -- /srv/t170/jobs/report.sh
[status 0]

The second run printed nothing and exited with 0, and the log shows why:

2026-11-24 15:16:01 [nightly] start: /srv/t170/jobs/slow.sh
2026-11-24 15:16:02 [nightly] skipped: previous run still active
    step 1
2026-11-24 15:16:06 [nightly] end: status 124 after 5s

The skipped line appears before the first run's output because the output is written to the log when the run ends.

Wrong usage is reported on standard error with status 2:

$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs
usage: cronjob.sh [-n NAME] [-t TIMEOUT] [-d LOG_DIR] -- COMMAND [ARG...]
[status 2]
$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -t 5x -- /srv/t170/jobs/report.sh
cronjob.sh: invalid timeout: '5x'
[status 2]
$ /srv/t170/bin/cronjob.sh -d /srv/t170/logs -n 'bad name' -- /srv/t170/jobs/report.sh
cronjob.sh: invalid job name: 'bad name'
[status 2]

The wrapper's log files grow with every run; rotate them with the script from lesson 165, which can itself run through the wrapper.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Scheduling Bash Scripts with cron and get answers drawn from it.

Signed-in readers only.