Skip to content

Instantly share code, notes, and snippets.

@gildas
Created November 26, 2020 03:18
Show Gist options
  • Save gildas/382b096f7270935e47d04a8c8b282b21 to your computer and use it in GitHub Desktop.
Save gildas/382b096f7270935e47d04a8c8b282b21 to your computer and use it in GitHub Desktop.
a sponge replacement in case it is too difficult to install moreutils
#!/usr/bin/env bash
function main() {
local APPEND=0
while (( "$#" )); do
# Replace --parm=arg with --parm arg
[[ $1 == --*=* ]] && set -- "${1%%=*}" "${1#*=}" "${@:2}"
case $1 in
-a|--append)
APPEND=1
;;
esac
shift
done
# Set all positional arguments back in the proper order
eval set -- "${ARGS[@]}"
out=$1
temp=$(mktemp "${out%%/*}/tmp-sponge.XXXXXXXX") &&
cat > "$temp" &&
if (( APPEND )) then
cat "$temp" >> "$out"
else
if [[ -f $out ]]; then
chmod --reference="$out" "$temp"
mv "$temp" "$out"
elif [[ -n $out ]]; then
cat $temp > $out
else
cat $temp
fi
fi &&
rm -f "$temp"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment