Curated articles, resources, tips and trends from the DevOps World.
Summary: This is a summary of an article originally published by CommandLineFu. Read the full original article here →
$ buffer(){ tty -s&&return; d=${1:-/tmp}; tmp=$(mktemp "$d/.b.XXXXXX")||return; trap 'rm -f "$tmp"' EXIT; cat>"$tmp"||{ rm -f "$tmp"; return 1; }; [ -z "$1" ]&&{ cat "$tmp"; rm -f "$tmp"; return 0; }; mv -f "$tmp" "$1"; } Issues & improvements Race conditions: the check for writability then mv is not fully atomic — another process could create/remove/change the target between the test and mv. Permissions and ownership: mv will preserve contents but the resulting file may have the temp file's permissions/ownership (mktemp default). Signal safety: if interrupted (SIGINT, SIGTERM) the temp file may remain. Portability: uses bash-compatible constructs but relies on mktemp and -a (POSIX [ -a ] is obsolete; better to use -e). Better error messages and exit status handling. Allow optional mode to write to stdout when no filename given. Support setting desired file mode (umask or chmod) and preserve atomic replace semantics. Enhanced version Uses safer existence test ([ -e ] not deprecated -a). Installs traps to clean up temp file on exit/signals. Preserves mode of the existing file (if it exists) or allows a chmod option. Attempts a safer atomic replace: write to temp in same directory as target when a filename is supplied (reduces window for cross-filesystem mv failure and preserves atomicity). If no filename given, writes temp contents to stdout. Returns non-zero on failure and prints concise errors to stderr. View this command to comment, vote or add to favourites View all commands by cryptology_codes Diff your entire server config at ScriptRock.com
Made with pure grit © 2025 Jetpack Labs Inc. All rights reserved. www.jetpacklabs.com