1

I have a the following in a bash script:

cmd="composer install"
`"$cmd"`

which results in:

composer install: command not found

However if I just run this in the same bash script instead:

composer install

it work without issue. What am I doing wrong?

3

Don't quote this variable expansion:

cmd="composer install"
$cmd

The variable is expanded, and because it's not quoted, the shell will proceed to split it up into words, so you do execute: "composer" "install" (instead of "composer install" as a single word)


Don't wrap it in backticks. This is wrong:

`$cmd`

That will execute the composer command, capture the stdout and then try to execute the output as a command.


One habit to get into is using bash arrays to build up commands. This is required because it's impossible for the shell to properly evaluate commands held in a single string when the command has arguments with whitespace. A fictitious example

cmd="composer install --users='fred barney'"

In this case $cmd will expand into 4 arguments, not the 3 you'd probably expect:

"composer" "install" "--users='fred" "barney'"

If this may affect you, arrays are the way to go:

cmd=( composer install --users='fred barney' )

This array has 3 elements. The way to execute that is thus (ugly but correct):

"${cmd[@]}"
0

You can use functions instead:

#!/bin/bash

function special_command {
  composer install
}

special_command

You can also pass variables this way:

#!/bin/bash

function special_ls {
  ls -ld $1
}
function normal_ls {
  ls $file
}

special_ls /var/tmp

file=/var/tmp
normal_ls

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.