Skip to content

Instantly share code, notes, and snippets.

@julien-f
Created February 22, 2022 11:44
Show Gist options
  • Save julien-f/0173a3cf7d65ee5a8760b28e9b7eb6f1 to your computer and use it in GitHub Desktop.
Save julien-f/0173a3cf7d65ee5a8760b28e9b7eb6f1 to your computer and use it in GitHub Desktop.
CLI to prepend a string to a file (compatible with POSIX shell, Bash or Dash)
#!/bin/sh
set -eu
if [ $# -eq 0 ] || [ "$1" = -h ] || [ "$1" = --help ]
then
cat <<EOF
Usage: $0 file prefix
Add a prefix to a file.
No new lines are added, either after the prefix or at the end of the file.
EOF
exit
fi
# Read the file without introducing or removing new lines at the end
content=$(cat "$1"; echo _)
content=${content%_}
printf '%s' "$2" "$content" > "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment