Dup Ver Goto 📝

Examples of eval in Bash

PT2/lang/bash/eval bash eval does not exist
To
20 lines, 104 words, 600 chars Page 'EvalExamples' does not exist.

Defining Functions With Variable Names

I use this to define shorthands for ssh'ing to hosts around my network

ssh_shortcut() {
  local SH="$1"
  local HOST="${2-$SH}"
  shift 2
  eval "$SH() { ssh \"$HOST\" $* \"\$@\"; }"
}

for s in m1 m2 m3 m4; do
  ssh_shortcut "$s"
done
ssh_shortcut m5 mandy
ssh_shortcut m6 micha
ssh_shortcut m6l micha ls

which then means that m1 will ssh into m1, and m5 will ssh into mandy, and m6l will ssh into micha and run ls. There is a slight shortcoming with quoting in that the arguments to be passed to ssh cannot include spaces and such.