Skip to content

Instantly share code, notes, and snippets.

@willb
Forked from sophwats/expenv.sh
Created December 2, 2019 19:48
Show Gist options
  • Select an option

  • Save willb/5c93b09176e006a2cd991ba9f2faf8e5 to your computer and use it in GitHub Desktop.

Select an option

Save willb/5c93b09176e006a2cd991ba9f2faf8e5 to your computer and use it in GitHub Desktop.

Revisions

  1. Sophie Watson created this gist Dec 2, 2019.
    38 changes: 38 additions & 0 deletions expenv.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    #!/bin/sh

    while getopts ":if:" opt; do
    case $opt in
    f)
    useFile=$OPTARG
    ;;
    \?)
    echo "Invalid option: -$OPTARG" >&2
    exit 1
    ;;
    :)
    echo "Option -$OPTARG requires an argument." >&2
    exit 1
    ;;
    i)
    inPlace=true
    ;;
    esac
    done

    if [ -n "$inPlace" ] && [ -z "$useFile" ]; then
    echo "Error: Option -i depends on option -f" >&2
    fi

    if [ -n "$inPlace" ]; then
    tmpFile=`mktemp`
    fi

    # Eval each line and redirect to tmpFile if set, otherwise to process stdout
    while read -r line; do
    eval "echo $line" >> "${tmpFile:-/proc/${$}/fd/1}"
    done < "${useFile:-/proc/${$}/fd/0}"

    # Overwrite file
    if [ -n "$inPlace" ]; then
    mv -- $tmpFile $useFile
    fi