Skip to content

Instantly share code, notes, and snippets.

@geoff-nixon
Created December 9, 2013 13:45
Show Gist options
  • Save geoff-nixon/7872454 to your computer and use it in GitHub Desktop.
Save geoff-nixon/7872454 to your computer and use it in GitHub Desktop.
Safely replace `backticks` with POSIX-style $(command substitutions) in scripts.
#!/bin/sh # tickoff -- G.Nixon, 2013. Public Domain.
# Safely replace backticks with POSIX "$()" style command substitutions.
# Takes a shell script (from stdin, or as parameters) and replaces pairs of
# backticks with $(substitutions), per line. If a backtick is unmatched
# or escaped, returns an error with the offending line number.
case "$1" in *elp|-h) echo 'Usage: tickoff [script ...]'; echo
echo ' Replace `backticks` with $(command substitutions).'; echo '
Takes shell script (from stdin, or as parameters) and replaces pairs of
backticks with $(substitutions), per line. If a backtick is unmatched
or escaped, returns an error with the offending line number.'; exit 0 ;; *)
t(){ sed 's/\`/\$\(/' ;}; tt(){ t|sed 's/\`/\)/' ;}; et(){ grep -lq '\\\`' ;}
at(){ grep -lq \` ;}; dt(){ o="$(cat)"; if $(echo "$o" | et); then
echo "Can't do escapes:" >&2; echo "$o" | grep -n '\\\`' >&2; return 1; fi
while $(echo "$o" |t|at); do o="$(echo "$o" |tt|dt)"; done; echo "$o" ;}
if [ x"$@" = x"" ]; then oo="$(dt)"; else oo="$(dt < "$@")"; fi
if [ $? != 0 ]; then exit 1; fi; if $(echo "$oo" | grep -lq \`); then
echo "Mismatched:" >&2; echo $(echo "$oo" | grep -n \`) >&2; exit 1; else
echo "$oo"
fi ;;
esac
@geoff-nixon
Copy link
Author

For those unaware, see why you want to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment