Skip to content

Instantly share code, notes, and snippets.

@sophwats
Created December 2, 2019 19:48
Show Gist options
  • Save sophwats/03b16c17f0488eca732a43a292726024 to your computer and use it in GitHub Desktop.
Save sophwats/03b16c17f0488eca732a43a292726024 to your computer and use it in GitHub Desktop.
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment