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:
var=$(foo ...)
: the assignment would not change$?
so$?
is still the foo's exit code.export
itself is a command soexport 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
Running R Scripts or Commands with Interpretor in Unix for Unix-Layman
How to Read a Sector Using a Bio Request in Linux Kernel
"Current" in Linux Kernel Code
How to Force a Firefox Page Refresh from Linux Console
Creating a Raw Printer Queue in Cups (Host) and Adding Them Through Cups (Client)
Adding a New System Call in Linux Kernel 3.3
How to Prefill Command Line Input
How to Capture Network Frames in a Kernel Module
The Meaning of Real, User, and Sys in Output of Linux Time Command
Systemd: "Environment" Directive to Set Path
Shell Script Working Fine Without Shebang Line? Why
How to Prevent Out of Memory (Oom) Freezes on Linux
Ssh Command Execution Hangs, Although Interactive Shell Functions Fine
How to Remove Warning About Storing Unencrypted Password After Committing File in Svn
How to Allocate a New Tls Area with Clone System Call
How to Check a File Exists and Execute a Command If Not