0

I tried the commands in a bash script.

#!/bin/bash
cmd='pgrep -d " " -f "python test.py"'
$cmd 

cmd2=(pgrep -d \" \" -f \"python test.py\")
${cmd2[@]}

Both don't work returning pgrep: only one pattern can be provided as you expect. however both work with eval command like the below.

eval $cmd
eval ${cmd2[@]}

The errors seem from using quote(") but I don't have any idea why and how eval command interacts with the quote in here though I have tried to understand with the below description.

DESCRIPTION
       The eval utility shall construct a command by concatenating arguments together, separating
       each with a <space>. The constructed command shall be read and executed by the shell.


EXAMPLES
          foo=10 x=foo
          y='$'$x
          echo $y
          $fooeval y='$'$x
          echo $y
          10

Could you give me the explanation?

SangminKim
  • 8,358
  • 14
  • 69
  • 125
  • Possible duplicate of [How to execute command stored in a variable?](https://stackoverflow.com/questions/4668640/how-to-execute-command-stored-in-a-variable) – sjsam Jan 22 '18 at 12:09
  • 3
    Don't store commands in variables. – sjsam Jan 22 '18 at 12:09

1 Answers1

0

Take a look at the output here and see if it helps.

showArgs(){
  test $# = 0 && return
  echo "arg:" "$1"
 shift
 showArgs "$@"
}
cmd='pgrep -d " " -f "python test.py"'
echo Without eval ---------
showArgs $cmd
echo With eval --------
eval showArgs $cmd

Also try set -x to enable debug output.

mncl
  • 161
  • 1
  • 5