0

So if I put some simple commands into a variable, and then call that variable at the beginning of the line, it actually uses those commands. For example:

yes@no:~$ nnn="ls -l Super"
yes@no:~$ $nnn
-rw-rw-rw- 1 yes yes 6 May 29 19:46 Super

But if I try it with anything that has any special characters, or if I try with something like case or if, it doesn't work:

yes@no:~$ nnn="ls -l|grep Super"
yes@no:~$ $nnn
ls: invalid option -- '\'
Try 'ls --help' for more information.

Or:

yes@no:~$ duper="if [[ ${ar} -eq 2 ]]; then echo yes; else echo no; fi"
yes@no:~$ "$duper"
if [[  -eq 2 ]]; then echo yes; else echo no; fi: command not found

Obviously there's something deeper here that I do not understand.

1 Answers1

0

The quote wrapping is escaping the special characters, so they are being treated as literals. To elicit the behaviour you are looking for, you would have to do

eval "$nnn"
eval "$duper"
bxm
  • 4,855
  • But everywhere I read, using eval is somehow 'evil' – user361323 Nov 05 '19 at 11:13
  • I can't speak for the morality of it :-) but for some things it's necessary – case in point. I would be inclined to ask what problem you are trying to solve by running commands in this manner? Perhaps there's another approach without resorting to evil eval. – bxm Nov 05 '19 at 11:31
  • I was just generally curious. it helps with understanding things on a more fundamental level, little by little. – user361323 Nov 05 '19 at 11:51