Preview and stage a configuration change
Keep a network change plan separate from writing a local candidate file.
Preview is the default action
A script that generates a candidate configuration should make the change visible before writing it. This exercise always prints the normalised plan. Only the explicit -a option publishes that same content into a virtual candidate file. Running the script without options leaves any existing candidate untouched.
Use getopts for a small portable interface and reject unknown options or leftover arguments before writing anything. The plan contains validated data, so the task is about the application boundary rather than parsing arbitrary device syntax. Device and port names remain fields, not shell commands.
Publish complete content
Build a complete report in a temporary file inside the destination directory, then rename it over the target. A trap cleans up the temporary file when the script exits. Using a temporary file on the same filesystem avoids exposing a partly written target during a normal successful publication.
This writes only candidate/access-ports.tsv in the browser workspace. It does not connect to a switch, replace an actual configuration or guarantee a safe production change. Real device changes require their own validation, authorisation, rollback and confirmation workflow. Keeping that boundary explicit lets you practise repeatable plan generation without confusing a local file operation with a live deployment.
printf 'device_id\tport\tvlan\n'
LC_ALL=C awk 'NR>1' plan.tsv | LC_ALL=C sort
Put it into practice.
Implement bash main.sh [-a]. Read validated plan.tsv with unique device_id<TAB>port<TAB>vlan rows and print the header plus rows sorted by device/port in LC_ALL=C. With no options, leave candidate/access-ports.tsv unchanged, including when it does not exist. With -a, replace that file with the complete printed plan; repeated apply runs replace, never append. Reject unknown options or positional arguments with nonzero exit and Usage: on stderr before changing files. Keep plan.tsv unchanged. This is a local candidate file, not a live device change.
See an explained solution
export LC_ALL=C
apply=no
while getopts ':a' option;do
case "$option" in a)apply=yes;;*)printf 'Usage: bash main.sh [-a]\n' >&2;exit 2;;esac
done
shift $((OPTIND-1))
[ "$#" -eq 0 ] || { printf 'Usage: bash main.sh [-a]\n' >&2;exit 2; }
render(){ printf 'device_id\tport\tvlan\n';awk 'NR>1' plan.tsv | sort; }
if [ "$apply" = no ];then render;exit;fi
mkdir -p candidate || exit 1
tmp=$(mktemp candidate/.ports.XXXXXX) || exit 1
trap 'rm -f "$tmp"' EXIT
render > "$tmp" || exit 1
cat "$tmp" || exit 1
mv "$tmp" candidate/access-ports.tsv || exit 1
The default operation is a non-mutating preview. Explicit apply publishes exactly the reviewed format through a staged file, while option validation prevents malformed invocations from changing the candidate.