Automation, from a shell script to a workflow · Lesson 3 of 8 · about 40 minutes

When a file arrives: jobs that start themselves

A supplier drops stock files into a folder, and each one has to be checked and loaded within seconds, with nobody watching. This lesson builds a job that starts the moment a file arrives, loads good files, sets bad ones aside with a reason, and never loads half a file or the same file twice. Then it sends broken, duplicate, unreadable, half-uploaded and 50-at-once files at it.

By the end you'll know

  • How to start a job the moment a file arrives, with a systemd path unit
  • What to check in a file before you trust it
  • Why every file must end up in processed/ or failed/, and never stay where it arrived
  • Why a file can be picked up before it's finished arriving, and the simple rule that stops it
  • How a job copes with many files at once

Before you start

  • You need: Vagrant and VMware Fusion or VirtualBox, as in Linux Lesson 7, and the practice folder: git clone https://github.com/Kwamib/automation-practice.git, or git pull in it if you have it.
  • This lesson uses permissions from Linux Lesson 5, services and journalctl from Linux Lesson 7, and awk from Linux Lesson 4.
  • Where commands run: on your own computer to build the server, then on the server, called feeds.
  • The output below is from real runs on November 18, 2026, at about 10:30am in New York (15:30 UTC).

The problem: work that arrives as files

So far, every job in this track has run on a clock. A lot of real automation runs when something happens instead. The most common "something" is a file arriving.

  • A supplier uploads a stock file every few hours.
  • A bank sends a payments file every night.
  • A warehouse system drops an orders file every few minutes.

Somebody's job is to pick each one up, check it, load it and move it out of the way, quickly and every time. Done by hand, it's tedious and easy to get wrong. Done by a careless script, it goes wrong in ways nobody sees for days:

  • A bad file is loaded, and wrong numbers end up in the system.
  • A file is loaded twice, and every number doubles.
  • Half a file is loaded, because the job picked it up while it was still arriving.
  • A file is lost, because the job crashed halfway and nobody knew.

The bookshop's version: its book supplier uploads stock files to a folder on a server. Each one lists books and how many copies the supplier has:

OUTPUT
isbn,title,quantity
9780141439518,Pride and Prejudice,12
9780451524935,Nineteen Eighty-Four,7

The first line names the three columns. Each line after that is one book: its ISBN (the 13-digit number every book has), its title, and a quantity. The job must add each file to the bookshop's stock list, within seconds of it arriving.

The server

On your own computer:

BASH
cd ~/Apps/automation-practice/feeds
vagrant up
vagrant ssh
  • cd .../feeds: Vagrant uses the Vagrantfile in the folder you're in. This one builds a server called feeds.
  • vagrant up: builds it and runs setup.sh, which makes a user for the job, the folders, the stock list and the watcher.
  • vagrant ssh: logs you in.

(On the server)

BASH
systemctl status feed-loader.path --no-pager | head -3
ls -l /srv/feeds
cat /srv/bookshop/stock.csv
OUTPUT
● feed-loader.path - Watch for supplier stock files arriving in /srv/feeds/incoming
     Loaded: loaded (/etc/systemd/system/feed-loader.path; enabled; preset: enabled)
     Active: active (waiting) since Wed 2026-11-18 15:28:49 UTC; 19s ago
total 12
drwxrwsr-x 2 feeds feeds 4096 Nov 18 15:28 failed
drwxrwsr-x 2 feeds feeds 4096 Nov 18 15:28 incoming
drwxrwsr-x 2 feeds feeds 4096 Nov 18 15:28 processed
isbn,title,quantity
9780141439518,Pride and Prejudice,3
9780451524935,Nineteen Eighty-Four,0
9780316769488,The Catcher in the Rye,5
  • systemctl status ... | head -3: is the watcher running? --no-pager prints it all at once, and head -3 keeps the first 3 lines. "active (waiting)" means it's watching, and nothing has arrived yet.
  • ls -l /srv/feeds: the three folders, in the long format (-l), with owners and permissions.
  • cat: the stock list before any file arrives: three books.

Every file moves through three folders, and ends in one of the last two:

FolderHolds
incoming/Files that have arrived and not been dealt with yet. Normally empty.
processed/Files that were checked and loaded, with the time they were loaded added to the name
failed/Files that were rejected, each with a .reason file saying why. Nothing from them was loaded.

The s in drwxrwsr-x is the setgid bit on a folder: every file created in it belongs to the folder's group, feeds, whoever creates it. The folders are owned by feeds, the job's own user, and your login (vagrant) is in the feeds group, so you can drop files in, as the supplier would.

Starting when a file arrives: a path unit

A timer runs a job at set times. A path unit runs a job when something changes on disk. feed-loader.path:

INI
[Unit]
Description=Watch for supplier stock files arriving in /srv/feeds/incoming

[Path]
# Start feed-loader.service whenever a .csv file is in the folder. Files still
# being uploaded should be named .part, and renamed when they're complete.
PathExistsGlob=/srv/feeds/incoming/*.csv

[Install]
WantedBy=paths.target
  • PathExistsGlob=/srv/feeds/incoming/*.csv: whenever at least one file matching *.csv is in the folder, start the service with the same name, feed-loader.service. * matches any name, and glob is the name for patterns like this.
  • Only .csv files count. A file named something.csv.part doesn't match. That matters later.
  • When the service finishes, systemd checks again. If .csv files are still there, it starts the service again.
  • WantedBy=paths.target: start watching when the server starts.

No polling. The older way is a cron job that looks in the folder every minute, which means a file waits up to a minute, and the job runs 1,440 times a day mostly to find nothing. The path unit is told by the kernel the moment something changes.

The service it starts, feed-loader.service:

INI
[Unit]
Description=Load supplier stock files into the bookshop's stock list

[Service]
Type=oneshot
User=feeds
Group=feeds
ExecStart=/usr/local/bin/feed-loader
TimeoutStartSec=5min
  • Type=oneshot: runs, finishes, done.
  • User=feeds, Group=feeds: runs as the job's own user, not root. It can read the incoming files, write the stock list, and very little else.
  • TimeoutStartSec=5min: a run still going after 5 minutes is stopped.

The loader

feed-loader, the script the service runs. Also on GitHub (opens in a new tab):

BASH
#!/usr/bin/env bash
# feed-loader: load the supplier's stock files into the bookshop's stock list.
#
# Every *.csv in incoming/ is checked. A good file is loaded and moved to
# processed/. A bad one is moved to failed/, with a .reason file saying why,
# and nothing from it is loaded: all of a file, or none of it.
#
# Exit codes: 0 every file loaded (or none waiting), 1 at least one file failed.
set -euo pipefail

FEED_DIR=${FEED_DIR:-/srv/feeds}
STOCK=${STOCK:-/srv/bookshop/stock.csv}
SETTLE_SECONDS=${SETTLE_SECONDS:-2}
LOCK=${LOCK:-/run/lock/feed-loader.lock}
HEADER="isbn,title,quantity"

incoming=$FEED_DIR/incoming
processed=$FEED_DIR/processed
failed=$FEED_DIR/failed
ledger=$FEED_DIR/loaded.sha256

log() { printf '%s feed-loader: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }

exec 9>"$LOCK"
if ! flock -n 9; then
	log "another run is going; it will pick these files up"
	exit 0
fi
touch "$ledger"

# check FILE: print why the file can't be loaded, and fail; or print nothing.
check() {
	local f=$1
	[ -r "$f" ] || { echo "it can't be read"; return 1; }
	[ -s "$f" ] || { echo "it's empty"; return 1; }
	[ -z "$(tail -c 1 "$f")" ] || { echo "the last line has no line ending: the file may be incomplete"; return 1; }
	! grep -q $'\r' "$f" || { echo "it has Windows line endings (CRLF)"; return 1; }
	[ "$(head -n 1 "$f")" = "$HEADER" ] || { echo "the first line isn't $HEADER"; return 1; }
	awk -F, '
		NR == 1 { next }
		NF != 3 { printf "line %d: expected 3 fields, found %d\n", NR, NF; bad = 1; exit }
		$1 !~ /^[0-9]+$/ || length($1) != 13 { printf "line %d: ISBN \"%s\" isn'\''t 13 digits\n", NR, $1; bad = 1; exit }
		$3 !~ /^[0-9]+$/ { printf "line %d: quantity \"%s\" isn'\''t a whole number\n", NR, $3; bad = 1; exit }
		{ rows++ }
		END { if (bad) exit 1; if (rows == 0) { print "it has no rows"; exit 1 } }
	' "$f" || return 1
	grep -qx "$(sha256sum <"$f" | cut -d' ' -f1)" "$ledger" && { echo "it's already been loaded: a file with exactly the same contents was loaded before"; return 1; }
	return 0
}

shopt -s nullglob
loaded=0 rejected=0
for f in "$incoming"/*.csv; do
	name=${f##*/}
	stamp=$(date -u +%Y%m%dT%H%M%SZ)

	# Wait until the file has stopped changing, in case it's still arriving.
	while [ -e "$f" ] && [ $(( $(date +%s) - $(stat -c %Y "$f") )) -lt "$SETTLE_SECONDS" ]; do
		log "waiting for $name to finish arriving ($(stat -c %s "$f") bytes so far)"
		sleep 1
	done
	[ -e "$f" ] || continue

	if ! reason=$(check "$f"); then
		mv -f -- "$f" "$failed/$stamp-$name"
		printf '%s\n' "$reason" >"$failed/$stamp-$name.reason"
		log "REJECTED $name: $reason (moved to failed/)"
		rejected=$((rejected + 1))
		continue
	fi

	# Load: each ISBN in the file sets that book's quantity, new books are added.
	# Written to a temporary file and renamed, so the stock list is never half written.
	before=$(( $(wc -l <"$STOCK") - 1 ))
	tmp=$(mktemp "${STOCK%/*}/.stock-XXXXXX")
	awk -F, -v OFS=, -v header="$HEADER" '
		FNR == 1 { next }
		!($1 in qty) { order[++n] = $1 }
		{ title[$1] = $2; qty[$1] = $3 }
		END { print header; for (i = 1; i <= n; i++) print order[i], title[order[i]], qty[order[i]] }
	' "$STOCK" "$f" >"$tmp"
	chmod 644 "$tmp"
	mv -f "$tmp" "$STOCK"
	after=$(( $(wc -l <"$STOCK") - 1 ))

	sha256sum <"$f" | cut -d' ' -f1 >>"$ledger"
	mv -f -- "$f" "$processed/$stamp-$name"
	log "loaded $name: $(( $(wc -l <"$processed/$stamp-$name") - 1 )) rows, $(( after - before )) new books (moved to processed/)"
	loaded=$((loaded + 1))
done

[ $((loaded + rejected)) -gt 0 ] && log "done: $loaded loaded, $rejected rejected"
[ "$rejected" -eq 0 ]

Taking it in order.

One run at a time

exec 9>"$LOCK" and flock -n 9 take a lock, so two loaders can never work on the same files at once. systemd won't start the service twice anyway; the lock protects you when someone runs the script by hand at the same time.

Wait until the file has stopped changing

BASH
while [ -e "$f" ] && [ $(( $(date +%s) - $(stat -c %Y "$f") )) -lt "$SETTLE_SECONDS" ]; do
  • stat -c %Y "$f": when the file was last changed, in seconds since 1970. -c picks what to show, and %Y is the modification time.
  • date +%s: the time now, in the same units.
  • The loop waits while the file was changed less than SETTLE_SECONDS (2) seconds ago, because it might still be arriving. You'll see why this alone isn't enough.

Check it before trusting it

The check function prints a reason and fails at the first problem it finds. In order:

CheckCommandCatches
Can it be read?[ -r "$f" ]A file the job's user isn't allowed to read
Is there anything in it?[ -s "$f" ]An empty file
Does the last line end properly?[ -z "$(tail -c 1 "$f")" ]A file cut off partway through a line
Normal line endings?grep -q $'\r' "$f"Windows line endings, which would make 12 look like 12\r
The right columns?[ "$(head -n 1 "$f")" = "$HEADER" ]A different layout, renamed or extra columns
Every row valid?the awk programWrong number of fields, an ISBN that isn't 13 digits, a quantity that isn't a whole number
Not seen before?sha256sum, then grep -qx in loaded.sha256The same file sent twice, under any name
  • [ -r FILE ] is true if the file can be read; [ -s FILE ] if it's not empty.
  • tail -c 1 prints the last character (-c counts characters). $( ) drops a final line ending, so if the last character is a line ending, the result is empty, which -z tests for.
  • $'\r' is how Bash writes a carriage return, the extra character at the end of every line in a Windows file.
  • awk -F, splits each line at commas (-F,). NR is the line number, NF the number of fields, and $1 and $3 the first and third fields. ~ /^[0-9]+$/ means "is made only of digits".
  • sha256sum gives a fingerprint of the contents: a long number that's the same for identical files and different for any change. Every loaded file's fingerprint is added to loaded.sha256, and grep -qx looks for an exact whole-line match (-x), quietly (-q).

All of a file, or none of it. A file with one bad row out of a thousand is rejected whole. Loading the good rows and skipping the bad one leaves the stock list half updated, with nobody sure which half.

Load it, without ever leaving the stock list half written

The awk program reads the stock list, then the new file. Each ISBN in the file sets that book's quantity; a new ISBN is added at the end. The result goes to a temporary file in the same folder, made by mktemp, and then mv renames it over the stock list in one step, so anyone reading the stock list sees the old version or the new one, never half of each. That's the same trick as Lesson 1's reports.

Setting a quantity, not adding to it, also means loading the same data twice can't double anything. The fingerprint check stops most repeats; this makes the rest harmless.

Always move the file out

Every file ends in processed/ or failed/, with the time added to its name, and a failed file gets a .reason file next to it. No file is ever left in incoming/. Spot the problem shows what happens when one is.

An exit code

[ "$rejected" -eq 0 ] is the last line, so the script exits 0 if every file was loaded, and 1 if any was rejected. systemd records that as the run succeeding or failing.

A good file arrives

BASH
cp /practice/feeds/samples/stock-good.csv /srv/feeds/incoming/
sleep 5
cat /srv/bookshop/stock.csv
journalctl -u feed-loader.service --no-pager -o short-iso | tail -3
OUTPUT
isbn,title,quantity
9780141439518,Pride and Prejudice,12
9780451524935,Nineteen Eighty-Four,7
9780316769488,The Catcher in the Rye,5
9780061120084,To Kill a Mockingbird,4
9780743273565,The Great Gatsby,9
9780547928227,The Hobbit,15
2026-11-18T15:41:17+00:00 feeds feed-loader[2559]: 2026-11-18T15:41:17Z feed-loader: done: 1 loaded, 0 rejected
2026-11-18T15:41:17+00:00 feeds systemd[1]: feed-loader.service: Deactivated successfully.
2026-11-18T15:41:17+00:00 feeds systemd[1]: Finished feed-loader.service - Load supplier stock files into the bookshop's stock list.
  • cp FILE FOLDER/: drops the file in, as the supplier would. sleep 5: waits 5 seconds.
  • journalctl -u feed-loader.service: the loader's log. -o short-iso gives readable times, and tail -3 the last 3 lines.

Within seconds, with nobody doing anything: two quantities updated (Pride and Prejudice 3 to 12, Nineteen Eighty-Four 0 to 7), three new books added, and The Catcher in the Rye, which wasn't in the file, left alone. The file itself is now in processed/.

Bad files

Four files at once: one with a bad row, one with the wrong columns, the good file again under a new name, and one only its owner can read:

BASH
cp /practice/feeds/samples/stock-bad-row.csv /practice/feeds/samples/stock-wrong-columns.csv /srv/feeds/incoming/
cp /practice/feeds/samples/stock-good.csv /srv/feeds/incoming/stock-good-again.csv
install -m 600 /practice/feeds/samples/stock-update.csv /srv/feeds/incoming/stock-private.csv
sleep 8
ls /srv/feeds/failed
cat /srv/feeds/failed/*.reason
OUTPUT
20261118T154231Z-stock-bad-row.csv         20261118T154233Z-stock-good-again.csv         20261118T154233Z-stock-private.csv         20261118T154233Z-stock-wrong-columns.csv
20261118T154231Z-stock-bad-row.csv.reason  20261118T154233Z-stock-good-again.csv.reason  20261118T154233Z-stock-private.csv.reason  20261118T154233Z-stock-wrong-columns.csv.reason
line 3: ISBN "978045152493" isn't 13 digits
it's already been loaded: a file with exactly the same contents was loaded before
it can't be read
the first line isn't isbn,title,quantity
  • install -m 600 FROM TO: copies a file and sets its permissions in one go. 600 means only its owner can read it.
  • cat failed/*.reason: prints every reason file. * matches any name.

Every one rejected, each with a reason a person can act on, and the stock list unchanged. The duplicate was caught by its contents, even under a new name. The bad-row file had a good first row, and none of it was loaded.

One more, from an earlier run: the update file with Windows line endings, made with sed 's/$/\r/' (replace the end of each line, $, with a carriage return and the end of the line):

OUTPUT
it has Windows line endings (CRLF)

The day everything was "can't be read"

My first run of this lab rejected every file I copied in, including the good one, with "it can't be read". The sample files on my computer could only be read by their owner, permissions 600, and cp gives the copy the same permissions as the original. The copies belonged to my login, and the loader, running as feeds, wasn't allowed to open them. The files made by sed and printf were fine, because those get the normal permissions.

That's one of the most common problems with real file feeds: the supplier's upload leaves files the receiving job can't read. It's why agreeing the details with whoever sends the files matters, permissions included. It's also why the loader checks: it set each file aside with a clear reason, instead of crashing on it or trying again forever.

Half a file

Now the classic bug. An upload over a slow connection arrives a bit at a time. This imitates one that sends 3 lines, pauses for 5 seconds, and sends the rest:

BASH
( head -n 3 /practice/feeds/samples/stock-update.csv; sleep 5; tail -n +4 /practice/feeds/samples/stock-update.csv ) > /srv/feeds/incoming/stock-slow.csv
sleep 3
journalctl -u feed-loader.service --no-pager -o short-iso | tail -4
cat /srv/bookshop/stock.csv
cat /srv/feeds/processed/*stock-slow.csv
  • ( ... ) > FILE: runs the commands in the brackets, and writes everything they print into one file.
  • head -n 3: the first 3 lines. tail -n +4: everything from line 4 on.
OUTPUT
2026-11-18T15:29:58+00:00 feeds feed-loader[2650]: 2026-11-18T15:29:58Z feed-loader: loaded stock-slow.csv: 2 rows, 0 new books (moved to processed/)
2026-11-18T15:29:58+00:00 feeds feed-loader[2650]: 2026-11-18T15:29:58Z feed-loader: done: 1 loaded, 0 rejected
...
isbn,title,quantity
9780141439518,Pride and Prejudice,10
9780451524935,Nineteen Eighty-Four,6
9780316769488,The Catcher in the Rye,5
isbn,title,quantity
9780141439518,Pride and Prejudice,10
9780451524935,Nineteen Eighty-Four,6
9780061120084,To Kill a Mockingbird,8
9780743273565,The Great Gatsby,2
9780547928227,The Hobbit,13

(This was the earlier run, before the good file had been loaded, which is why the stock list has only three books.)

The loader loaded 2 rows. The file in processed/ has 5. Here's what happened:

  1. The first 3 lines arrived, and the path unit started the loader at once.
  2. The loader waited for the file to stop changing. The upload was paused, so after 2 seconds it looked finished.
  3. The 2 rows passed every check: each line was complete, because the pause came at the end of a line.
  4. The loader loaded them, and moved the file to processed/.
  5. The upload carried on, and wrote the last 3 lines into the file in processed/. Moving a file doesn't stop a program that's already writing to it.

Three books' stock never loaded, and nothing reported a problem. Waiting for a file to settle helps, but any upload that pauses longer than the wait gets through.

The fix: upload, then rename

The reliable fix is a rule both sides follow: the sender writes the file under a name the job ignores, and renames it when it's complete. Here, that's .part on the end:

BASH
cp /practice/feeds/samples/stock-update.csv /srv/feeds/incoming/stock-update.csv.part
sleep 4
ls /srv/feeds/incoming
mv /srv/feeds/incoming/stock-update.csv.part /srv/feeds/incoming/stock-update.csv
sleep 4
journalctl -u feed-loader.service --no-pager -o short-iso | tail -2
cat /srv/bookshop/stock.csv
OUTPUT
stock-update.csv.part
2026-11-18T15:42:54+00:00 feeds systemd[1]: feed-loader.service: Deactivated successfully.
2026-11-18T15:42:54+00:00 feeds systemd[1]: Finished feed-loader.service - Load supplier stock files into the bookshop's stock list.
isbn,title,quantity
9780141439518,Pride and Prejudice,10
9780451524935,Nineteen Eighty-Four,6
9780316769488,The Catcher in the Rye,5
9780061120084,To Kill a Mockingbird,8
9780743273565,The Great Gatsby,2
9780547928227,The Hobbit,13
  • For 4 seconds, stock-update.csv.part sat in incoming/ untouched. It doesn't match *.csv, so the path unit never started the loader for it.
  • mv renamed it, and the loader picked it up straight away and loaded all five rows.

A rename within one folder happens in a single step, so there's never a moment when stock-update.csv exists but is incomplete. Most file-transfer tools can do this for you: many SFTP clients have a "upload to a temporary name, then rename" setting.

50 files at once

Suppliers sometimes send a backlog. Fifty files, each written as .part and then renamed, as fast as the shell can go:

BASH
for i in $(seq -w 1 50); do printf 'isbn,title,quantity\n97800000000%s,Book %s,%s\n' $i $i $i > /srv/feeds/incoming/.burst-$i.part && mv /srv/feeds/incoming/.burst-$i.part /srv/feeds/incoming/burst-$i.csv; done
sleep 15
ls /srv/feeds/incoming | wc -l
ls /srv/feeds/processed | grep -c burst
grep -c '^97800000000' /srv/bookshop/stock.csv
journalctl -u feed-loader.service --no-pager -o short-iso | grep 'done:' | tail -2
  • for i in $(seq -w 1 50); do ...; done: repeats the commands 50 times, with i set to 01, 02, up to 50. -w pads the numbers to the same width.
  • printf: prints text, with each %s replaced by the next value. \n is a new line.
  • &&: renames only if writing worked.
  • wc -l: counts lines; here, the files left in incoming/.
  • grep -c PATTERN: counts matching lines. ^ means "at the start of the line".
OUTPUT
0
50
50
2026-11-18T15:30:43+00:00 feeds feed-loader[2731]: 2026-11-18T15:30:43Z feed-loader: done: 24 loaded, 0 rejected
2026-11-18T15:30:43+00:00 feeds feed-loader[3408]: 2026-11-18T15:30:43Z feed-loader: done: 26 loaded, 0 rejected

All 50 loaded, none left behind, in two runs. The first file started the loader, which waited for it to settle; by the time it listed the folder, 24 files were there. When it finished, the path unit looked again, found the other 26, and started it once more. Nothing was missed, and the job didn't run 50 times.

Who tells you

systemctl status shows how the last run went, and a run with any rejected file ends as failed:

BASH
systemctl status feed-loader.service --no-pager | head -5
OUTPUT
○ feed-loader.service - Load supplier stock files into the bookshop's stock list
     Loaded: loaded (/etc/systemd/system/feed-loader.service; static)
     Active: inactive (dead) since Wed 2026-11-18 15:30:43 UTC; 23s ago
TriggeredBy: ● feed-loader.path
    Process: 3408 ExecStart=/usr/local/bin/feed-loader (code=exited, status=0/SUCCESS)
  • TriggeredBy: feed-loader.path: the service is started by the watcher, not by a timer or a person.
  • status=0/SUCCESS: the last run loaded everything.

Nobody reads systemctl status at 3am, though. On a real server, this job gets the same hc-ping as Lesson 2: one line, ExecStopPost=/usr/local/bin/hc-ping, and a rejected file sends an alert within seconds.

And the heartbeat catches the other failure, too. If the supplier normally sends a file every few hours, give the check a period of a day. If a whole day passes with no file loaded, you hear about it, whether the supplier's upload broke, their password expired, or they simply stopped sending. For a file feed, "nothing arrived" is a failure, and only something expecting a file can notice it.

Clean up

BASH
exit

(On your own computer)

BASH
vagrant destroy -f

-f deletes the server without asking you to confirm.

On a real server

  • Agree the rules with the sender, and write them down: the file name pattern, the columns, the line endings, the permissions, and "write as .part, then rename". Most feed problems are two sides assuming different things.
  • Tell the sender when a file fails, with the reason. They can usually fix it faster than you can.
  • Use a real CSV reader for real CSV files. This lesson's files never have commas inside a field. Real ones do ("Smith, John"), and splitting on commas breaks them. Python's csv module handles them properly: see the Python track's Files and data.
  • Clean out processed/ and failed/ on a schedule, with something like Lesson 1's prune-backups, or they fill the disk.
  • Give the sender their own login, limited to the upload folder, never a shared account.
  • Send failures and silence to a heartbeat, as in Lesson 2.

Spot the problem

Work out what's wrong before you read the explanation.

"No files have loaded since lunchtime." A team's loader checks each file and, if it's bad, logs an error and moves on to the next file, leaving the bad one in incoming/ "so someone can look at it". One afternoon, a supplier sends a file with a bad row. The loader logs the error and finishes. The path unit sees a .csv file still in incoming/, and starts the loader again, which logs the same error, and again, and again. After a few seconds of this, systemd's safety limit on starting a unit too often steps in, and the watcher gives up. Every file after that sits in incoming/, unloaded, and nothing more is logged. What's wrong? A bad file left in incoming/ keeps the path unit's condition true, so the job loops on it until systemd stops it, and then it stops watching altogether. The fix: every file must leave incoming/, whatever happens: to processed/ if it loaded, to failed/ with a reason if it didn't, as feed-loader does. Then check: drop a bad file in, and confirm the next good file still loads.

Keep this

ToUse
Start a service when files appearA path unit with PathExistsGlob=/folder/*.csv
Is the watcher running?systemctl status NAME.path
Files in a folder belong to its groupchmod g+s FOLDER (the setgid bit)
Copy a file with chosen permissionsinstall -m 644 FROM TO
When a file last changed, in secondsstat -c %Y FILE
Can it be read? Is it empty?[ -r FILE ], [ -s FILE ]
Does it end with a line ending?[ -z "$(tail -c 1 FILE)" ]
Does it have Windows line endings?grep -q $'\r' FILE
A fingerprint of a file's contentssha256sum < FILE
Is this exact line in a file?grep -qx LINE FILE
Replace a file in one stepWrite to a temporary file in the same folder, then mv it
Upload safelyWrite as NAME.part, then mv NAME.part NAME

Where you are now

You've built a job that starts the moment a file arrives, with no timer and no polling. It checks every file before trusting it, loads good ones in full, sets bad ones aside with a reason, recognizes a file it's seen before, and never leaves anything in incoming/. You've seen it load half a file when the upload paused, and fixed that for good with a rename. And you've seen it take 50 files at once in two runs. Lesson 4 moves from files to people: setting up a new starter's access with a script, and removing every trace of it when they leave.

Check yourself

  1. What starts feed-loader.service when a file arrives?

  2. A file has one bad row out of a thousand. What does the loader do?

  3. The same file arrives twice under different names. How is the second one caught?

  4. The slow upload paused for 5 seconds. Why was only part of it loaded?

  5. Why does writing as .part, then renaming, stop half files being loaded?

  6. Why must a rejected file be moved out of incoming/?

Key terms

  • File feed: a regular delivery of files from another system or company, to be picked up and processed.
  • Path unit: a systemd unit that starts a service when something happens on disk, such as a file appearing.
  • Glob: a filename pattern like *.csv, where * matches anything.
  • Setgid folder: a folder whose new files belong to its group, whoever creates them.
  • Fingerprint (hash): a short value computed from a file's contents, the same for identical files; sha256sum makes one.
  • All or nothing: load a whole file or none of it, never part.
  • Write then rename: write a file under a temporary name and rename it when it's complete, so nobody ever sees half of it.

Go deeper

  • Earlier lessons: Permissions and users for chmod, groups and the setgid bit, Services and logs with systemd for units and journalctl, and Working with text for awk.
  • The Python track's Files and data, for reading real CSV files properly.
  • systemd.path (opens in a new tab), for PathExistsGlob and the other ways a path unit can watch.
  • Try: make a file with a comma inside a title (9780000000001,"Smith, John",5) and see what the loader says. Then change SETTLE_SECONDS to 10 in a copy of the script, rerun the slow upload, and work out why it now loads all five rows, and why that still isn't a real fix.