4

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

php="php"
options="-l"

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
   fi
done

How can I do this?

Update:

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

Please have a look, it could also help you.

1 Answer 1

6

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

Ex.

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

then

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

giving

$ echo "$result"
drwxrwxr-x 2 user user 4096 Apr 20 08:07 foo
5
  • Thank you! Could you edit your answer to add quotes on $cmd too? (it could be a command with spaces in it). Commented Apr 24, 2017 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). Commented Apr 24, 2017 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? Commented Apr 24, 2017 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
    Commented Apr 24, 2017 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 :/ Commented Apr 24, 2017 at 14:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .