Skip to content

Instantly share code, notes, and snippets.

@mjambon
Last active September 19, 2018 20:14
Show Gist options
  • Save mjambon/3bb1c1abb261f0d7aa8dca23ab8af809 to your computer and use it in GitHub Desktop.
Save mjambon/3bb1c1abb261f0d7aa8dca23ab8af809 to your computer and use it in GitHub Desktop.
Editing a bash script while it's running
#! /bin/bash
#
# Illustrate what happens when editing a script while it's running.
#
# This happens when saving the file in emacs, for example, but not with
# 'sed -i' because the latter deletes the old file before writing a new one.
# See https://unix.stackexchange.com/a/88572/46435 for an explanation.
#
set -eu
me="$0"
# We're about to append this command to the current script.
cmd="date; undo_append"
orig_size=$(cat "$me" | wc -c)
undo_append() {
echo "Truncating '$me' back to its original state."
truncate "$me" -s "$orig_size"
}
# Append the 'date' and 'undo_append' commands to this script.
echo "$cmd" >> "$me"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment