Created
September 18, 2015 15:41
-
-
Save eriknomitch/d36c797ac26f8e97ffca to your computer and use it in GitHub Desktop.
Zsh script to prepend a file with string(s)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/zsh | |
# ================================================ | |
# PREPEND ======================================== | |
# ================================================ | |
# Prepends a string to a target file | |
# ------------------------------------------------ | |
# TRAP->TERM ------------------------------------- | |
# ------------------------------------------------ | |
trap "exit 1" TERM | |
local TOP_PID=$$ | |
# ------------------------------------------------ | |
# UTILITY ---------------------------------------- | |
# ------------------------------------------------ | |
function _exit_fatal() { | |
echo "fatal: $1" | |
kill -s TERM $TOP_PID | |
} | |
# ------------------------------------------------ | |
# MAIN ------------------------------------------- | |
# ------------------------------------------------ | |
# | |
# Validate target file | |
# ------------------------------------------------ | |
local _target=$1 | |
if [ $# -lt 1 ] ; then | |
_exit_fatal "No target file given." | |
fi | |
test -e $_target || _exit_fatal "The target '$_target' does not exist." | |
test -f $_target || _exit_fatal "The target '$_target' is not a file." | |
test -w $_target || _exit_fatal "The target '$_target' is not writable." | |
# Validate string(s) to prepend | |
# ------------------------------------------------ | |
if [ $# -lt 2 ] ; then | |
_exit_fatal "No string(s) given to prepend to target file given." | |
fi | |
shift | |
local _to_prepend="$*" | |
# Create a temporary file for merger | |
# ------------------------------------------------ | |
local _temporary_file_path=`mktemp "/tmp/\`basename $0\`.XXXX"` | |
if [[ $? != 0 ]] ; then | |
_exit_fatal "Could not create a temporary file in '/tmp' with mktemp." | |
fi | |
# Prepend/merge the temporary file | |
# ------------------------------------------------ | |
if ! ( echo $_to_prepend >> $_temporary_file_path && cat $_target >> $_temporary_file_path ) ; then | |
_exit_fatal "Could not prepend the inputs to the temporary file at '$_temporary_file_path'." | |
fi | |
# Overwrite the original target | |
# ------------------------------------------------ | |
if ! mv $_temporary_file_path $_target ; then | |
_exit_fatal "Could not move/overwrite the original target file at '$_target' with the temporary file at '$_temporary_file_path'." | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment