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.

Revisions

  1. gildas created this gist Nov 26, 2020.
    37 changes: 37 additions & 0 deletions sponge
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    #!/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 "$@"