Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a pretty simple script that is something like the following:

#!/bin/bash  VAR1="$1" MOREF='sudo run command against $VAR1 | grep name | cut -c7-'  echo $MOREF 

When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the $MOREF variable, I am able to get output.

How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?

like image 261
John Avatar asked Jan 10 '11 20:01

John


People also ask

How do you assign the output of a command to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'

How do you save the output of a command to a variable in Linux?

Here are the different ways to store the output of a command in shell script. You can also use these commands on terminal to store command outputs in shell variables. variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name=`command` variable_name=`command [option ...]

How do you set a variable in Linux command line?

We can set variables for a single command using this syntax: VAR1=VALUE1 VAR2=VALUE2 ... Command ARG1 ARG2...


1 Answers

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.

like image 112
Andy Lester Avatar answered Sep 28 '22 06:09

Andy Lester