withenv (939B)
1 #!/bin/sh 2 set -e 3 4 ENVFILE="-" 5 TAC="tac" 6 which tac >/dev/null 2>&1 && TAC="tac" || TAC="tail -r" 7 8 while :; do 9 case $1 in 10 -e|--export) EXPORT=1; shift ;; 11 -i|--ignore) IGNORE=1; shift ;; 12 -f|--file) ENVFILE="$2"; shift 2 ;; 13 --) break ;; 14 -*) echo "Invalid option $1"; exit 1 ;; 15 *) break ;; 16 esac 17 done 18 19 subst() { 20 cat "$1" \ 21 | { tee /dev/fd/3 \ 22 | sha1sum \ 23 | awk '{print "SHA1SUM=" $1}'; \ 24 } 3>&1 \ 25 | $TAC \ 26 | xargs sh -c 'printf "%s\n" "${@}" | '"$TAC"' | env "$0" envsubst' -- 27 } 28 29 if [ "$IGNORE" = 1 ]; then 30 ENVARGS="-i" 31 fi 32 33 if [ "$EXPORT" = 1 ]; then 34 subst "$ENVFILE" | sed 's/^\([^=]*\)=\(.*\)$/export \1="\2"/' 35 exit 0 36 fi 37 38 fifo="$(mktemp -d)/fifo" 39 mkfifo "$fifo" 40 ( 41 subst "$ENVFILE" | tr '\n' '\0' 42 [ "$#" -gt 0 ] && printf "%s\0" "$@" 43 rm -rf "$(dirname "$fifo")" 44 ) >> "$fifo" & 45 46 exec xargs -0 -a "$fifo" env $ENVARGS