Skip to content
Visual explainer 3h 30m to learn 5 steps

Scripts for real admin tasks

Automate user creation, disk checks and reports with safe, idempotent scripts.

By Invicly Tech, , in Linux Administration (RHCSA-style). About 10 minutes to read.

Topic 34 of 42

In short

Good admin scripts are idempotent: running them twice leaves the system in the same state as running them once. They check before changing, log what they did and fail loudly. Typical examples are bulk user creation, disk space alerts and daily health reports.

Explained simply

Admin scripts do real jobs on real servers: create 50 user accounts, warn when a disk is almost full, send a morning report. A small mistake in such a script can lock people out or delete data, so they need more care than a quick one-liner.

The most important habit is to make scripts idempotent. That word means running the script twice gives the same result as running it once. A script that creates a user should first check if the user exists. Then you can rerun it safely after a failure.

Good scripts also tell you what they did. Instead of printing to a screen nobody watches, send messages to the system journal with logger. Later you can search them with journalctl, together with everything else that happened on the server.

Finally, let a tool check your work. shellcheck reads a script and points out common bugs, such as missing quotes, before they hurt you in production.

Press Play on a diagram to walk through it one step at a time.

CycleIdempotent automation loop
  1. 1
    Check current state

    Does the user, file or setting exist?

  2. 2
    Compare with desired state
  3. 3
    Change only if needed
  4. 4
    Log the action

    logger -t script for the journal.

  5. 5
    Verify and exit with a status
  6. Back to step 1
FlowLife of a safe admin script
  1. 1
    Write

    Strict mode, functions, checks

  2. 2
    shellcheck

    Fix every warning

  3. 3
    Dry run

    --dry-run prints planned changes

  4. 4
    Run on a test VM

    Then run again: nothing should change

  5. 5
    Schedule

    systemd timer, logs in the journal

  6. 6
    Watch the exit status

    Alert on failure

In depth

Patterns for idempotent changes

Each kind of change has a check-then-act pattern. Users: id NAME || useradd NAME. Groups: getent group NAME || groupadd NAME, or simply groupadd -f. Folders: mkdir -p, or install -d -m 750 -o app -g app /srv/app, which also fixes owner and mode. A line in a config file: grep -qxF 'line' file || echo 'line' >> file. Services: systemctl enable --now is already idempotent.

Avoid commands that add something every time they run, such as a plain echo >> into a config file or useradd without a check. Use a --dry-run flag that prints what would change; it makes reviews easy and catches mistakes before they happen. Tools like Ansible are built around these same ideas.

CompareNot idempotent vs idempotent
Breaks on rerun
  • useradd ana fails: user exists
  • echo line >> file adds duplicates
  • mkdir dir fails if it exists
  • sed -i 's/a/aa/' grows every run
Safe to rerun
  • id ana || useradd ana
  • grep -qxF line file || echo line >> file
  • install -d -m 750 dir
  • Set exact values, not relative changes

Logging to the journal

logger -t mkusers "created ana" writes a message with the tag mkusers to the system log, which on systemd machines is the journal. journalctl -t mkusers shows only your script's messages, and -p sets a priority: logger -p user.err marks it as an error, so journalctl -p err finds it next to other errors.

To capture everything a script prints without changing every line, redirect it at the top: exec > >(logger -t myscript) 2>&1. Or run the whole script through systemd-cat -t myscript ./script.sh. When a script runs from a systemd timer, its output goes to the journal under the service name anyway, so a plain echo is enough.

  • journalctl -t mkusers --since today
  • journalctl -p warning -t diskcheck
  • logger -s also prints the message to stderr

Disk checks that catch both problems

A disk can fill up in two ways: no space left, or no inodes left. An inode is a small record for each file, and a filesystem has a fixed number of them, so millions of tiny files can exhaust inodes while df -h still shows free space. A good check looks at both: df --output=pcent and df --output=ipcent.

Check every real filesystem, not just /. df -x tmpfs -x devtmpfs -x overlay skips virtual ones. Use a warning and a critical threshold, such as 80 and 90 percent, and exit with a non-zero status when a limit is hit, so a timer's OnFailure= or a monitoring system can react.

shellcheck in practice

shellcheck script.sh prints warnings with codes and a link to a wiki page explaining each one. The most common: SC2086, double quote to prevent globbing and word splitting; SC2164, use cd ... || exit in case cd fails; SC2046, quote $(...) to prevent splitting; SC2155, declare and assign separately to avoid masking return values.

Install it with dnf install ShellCheck (from EPEL on RHEL) or apt install shellcheck. Run it in your editor and in CI, so a script never reaches a server with known issues. If a warning is truly wrong for one line, silence just that line with a comment such as # shellcheck disable=SC2086 directly above it, and say why.

Handling secrets and input files

Bulk-user scripts often need initial passwords. Never put passwords in the script itself or in a world-readable CSV. Generate a random one per user, for example openssl rand -base64 12, set it with chpasswd, which reads name:password lines from standard input, and force a change at first login with chage -d 0. Write the list only to a file with mode 600, or hand passwords over another way.

Treat input files as untrusted. Skip a header line, ignore blank lines and comments, trim Windows line endings, and check each field against an allowed pattern, such as a lowercase name of 1 to 32 characters, before passing it to useradd.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Bulk-create users from a CSV~40m
  2. 2
    Alert on low disk space~40m
  3. 3
    Log script output to the journal~40m
  4. 4
    Make scripts idempotent and re-runnable~40m
  5. 5
    Lint scripts with shellcheck~40m

Key points

  • Test for existence first, for example id user before useradd.
  • logger sends messages to the journal so you can find them with journalctl -t.
  • Run shellcheck on every script to catch quoting and logic bugs.
  • Schedule scripts with timers and monitor their exit status.

Key terms

Tap a card to flip it. 0/4 known

Examples

bash
#!/usr/bin/env bash
set -euo pipefail
# users.csv lines: name,group
while IFS=, read -r name group; do
  getent group "$group" >/dev/null || groupadd "$group"
  if id "$name" &>/dev/null; then
    logger -t mkusers "skip $name: exists"
  else
    useradd -m -G "$group" "$name" && logger -t mkusers "created $name"
  fi
done < users.csv
use=$(df --output=pcent / | tail -1 | tr -dc 0-9)
(( use < 90 )) || logger -p user.warning -t diskcheck "root at ${use}%"

Idempotent bulk user creation and a disk usage alert.

Bulk users from a CSV with random passwords

HR sends new_staff.csv with a header line and rows like name,group. Step 1: skip the header, strip Windows line endings and validate each name. Step 2: create missing groups and users only; existing ones are skipped and logged. Step 3: give each new user a random password, force a change at first login, and write the passwords to a root-only file. Running the script a second time changes nothing.

bash
#!/usr/bin/env bash
set -euo pipefail
out=/root/new-passwords.txt; umask 077
tail -n +2 "${1:?usage: $0 FILE.csv}" | tr -d '\r' | while IFS=, read -r name group; do
  [[ $name =~ ^[a-z][a-z0-9_-]{0,31}$ ]] || { logger -t mkusers "bad name: $name"; continue; }
  groupadd -f "$group"
  if id "$name" &>/dev/null; then logger -t mkusers "skip $name"; continue; fi
  useradd -m -G "$group" "$name"
  pw=$(openssl rand -base64 12)
  echo "$name:$pw" | chpasswd && chage -d 0 "$name"
  echo "$name $pw" >> "$out"
  logger -t mkusers "created $name in $group"
done

Space and inode check for every filesystem

Step 1: list real filesystems with their use and inode use as plain numbers. Step 2: compare each with the limit and log a warning with logger. Step 3: remember whether anything was over the limit and exit 1 if so, so the timer's service shows as failed and an OnFailure= alert can fire. Run it every 15 minutes from a timer.

bash
#!/usr/bin/env bash
set -euo pipefail
limit=${1:-90}; bad=0
while read -r mnt pcent ipcent; do
  p=${pcent%\%}; i=${ipcent%\%}
  [[ $i == - ]] && i=0          # some filesystems report no inodes
  if (( p >= limit || i >= limit )); then
    logger -p user.warning -t diskcheck "$mnt space ${p}% inodes ${i}%"
    bad=1
  fi
done < <(df --output=target,pcent,ipcent -x tmpfs -x devtmpfs -x overlay | tail -n +2)
exit "$bad"

Quick reference

  • Idempotent checks: id USER ||, getent group G ||, grep -qxF LINE FILE ||
  • install -d -m 750 -o app -g app DIR creates a folder with exact owner and mode
  • logger -t TAG -p user.warning "msg"; read with journalctl -t TAG
  • exec > >(logger -t TAG) 2>&1 sends all script output to the journal
  • df --output=target,pcent,ipcent checks space and inodes in one pass
  • echo 'user:pass' | chpasswd, then chage -d 0 user forces a new password
  • shellcheck script.sh before every commit; fix SC2086 quoting first
  • Run the script twice on a test VM: the second run must change nothing

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which line is idempotent?

Question 2

2df -h shows 40% used, yet the app gets No space left on device. What should you check?

Question 3

3How do you show only the messages your script logged with logger -t backup?

Question 4

4What does shellcheck warning SC2086 tell you?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Log a test message with the tag practice at warning level, then find it in the journal by tag and by priority.

  2. Exercise 2medium

    Write a script that makes sure the line 'net.ipv4.ip_forward = 1' exists exactly once in /etc/sysctl.d/90-forward.conf and applies it. Run it twice and prove the file has one line.

  3. Exercise 3hard

    Add a --dry-run option to a user-creation script so it prints each useradd it would run without changing anything.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What does idempotent mean in simple words?
Doing it once or ten times leaves the system in the same final state. It makes reruns after a failure safe.
Should I write admin scripts in bash or use Ansible?
For one server and simple tasks, a careful bash script is fine. For many servers, or when you need a clear record of desired state, a tool like Ansible is easier to maintain.
How do I give users an initial password safely?
Generate a random password per user, set it with chpasswd, force a change at first login with chage -d 0, and pass it on through a private channel. Never hard-code passwords in scripts.
Where do I see the output of a script run by a systemd timer?
In the journal under the service name: journalctl -u NAME.service. Anything the script prints is captured automatically.

Go deeper

ShareXLinkedInWhatsApp