I would like to run a command made of several "pieces".


for f in `git diff-index --cached --name-only HEAD | grep -e '\(php\|phtml\)$'`; do
   if [ -f $f ]; then
       # Here I want to run my command defined
       # in $php and $options and put the result in
       # $php_lint var
       # like this command would do:
       # php_lint=$(php -l $f)
       # but with something like that:
       # php_lint=eval $php $options $f

How can I do this?


After struggle on a particular point, I asked this question :

Please have a look, it could also help you.


Put the options in an array, and expand it as "${options[@]}"


$ cmd=ls
$ options=(-a -l -d)
$ f="foo"


$ result=$("$cmd" "${options[@]}" "$f")


$ echo "$result"
drwxrwxr-x 2 user user 4096 Apr 20 08:07 foo
  • Thank you! Could you edit your answer to add quotes on $cmd too? (it could be a command with spaces in it). – darckcrystale Apr 24 '17 at 13:56
  • @darckcrystale you may find that if $cmd contains spaces, that also needs to be passed as an array (otherwise it will appear as a single string - I can't think of any actual commands that contain spaces - only commands + arguments). – steeldriver Apr 24 '17 at 13:59
  • You're right, it could be command with options. Do I need to do like with the $options var? Or should I set command in $cmd, and all options in $options var? – darckcrystale Apr 24 '17 at 14:02
  • Strictly speaking, it is actually possible: fname=new$'\n'line.sh; printf '#!/bin/sh\necho "Hello world"\n' > "$fname"; chmod 755 "$fname"; ./"$fname". Anyone who does this, of course, deserves what they get. – terdon Apr 24 '17 at 14:03
  • @steeldriver The problem is for example the command could be something like docker exec <container name> <command> <options>, in this case, the $cmd could be docker and options exec, <container name>, <command>, <options>. That's sound a bit weird to me :/ – darckcrystale Apr 24 '17 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.