Assigning Output of a Command to a Variable(Bash)

How do I set a variable to the output of a command in Bash?

In addition to backticks `command`, command substitution can be done with $(command) or "$(command)", which I find easier to read, and allows for nesting.

OUTPUT=$(ls -1)
echo "${OUTPUT}"

MULTILINE=$(ls \
-1)
echo "${MULTILINE}"

Quoting (") does matter to preserve multi-line variable values; it is optional on the right-hand side of an assignment, as word splitting is not performed, so OUTPUT=$(ls -1) would work fine.

Bash, assigning command output to a variable

The problem is that your command does not print to STDOUT but to STDERR.

Using:

TMP=$(nginx -v 2>&1)

will solve your issue, see here for more details.

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

How to assign the output of a command to a variable while checking if the command was successful?

You can just

MESSAGE=$(ls ...)
if [[ $? -eq 0 ]]; then
success
else
failure
fi
export MESSAGE

Points:

  1. var=$(foo ...): the assignment would not change $? so $? is still the foo's exit code.
  2. export itself is a command so export var=$(foo ...)'s exit code would overwrite foo's exit code.

There ARE scenarios (syntax errors; assigning to readonly vars; ...) where var=value may change $? and export may fail. Examples:

[STEP 101] $ true
[STEP 102] $
[STEP 103] $ var=${:}
bash: ${:}: bad substitution
[STEP 104] $ echo $?
1
[STEP 105] $ export var=${:}
bash: var=${:}: bad substitution
[STEP 106] $ echo $?
1
[STEP 107] $

How to assign the output of a Bash command to a variable?

Try:

pwd=`pwd`

or

pwd=$(pwd)

Notice no spaces after the equals sign.

Also as Mr. Weiss points out; you don't assign to $pwd, you assign to pwd.

Assign the output of command to variable

Add an echo:

tString="This is my name"
var=$(echo $tString | cut -d' ' -f1)

(Also mentioned here 2 seconds before I posted my answer)



Related Topics



Leave a reply



Submit