linux - [Solved-5 Solutions] How to set a variable to the output from a command in Bash ? - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

How to set a variable to the output from a command in Bash ?

Linux - Solution 1:

In addition to the backticks, you can use $().

OUTPUT="$(ls -1)"
echo "${OUTPUT}"
click below button to copy the code. By - Linux tutorial - team

Quoting (") does matter to preserve multi-line values.

Linux - Solution 2:

You're using the wrong kind of apostrophe. You need `, not '. This character is called "backticks" (or "grave accent").

#!/bin/bash

VAR1="$1"
VAR2="$2"

MOREF=`sudo run command against $VAR1 | grep name | cut -c7-`

echo $MOREF
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

The $(command) works as well, and it also easier to read, but note that it is valid only with bash or korn shells (and shells derived from those), so if your scripts have to be really portable on various Unix systems, you should prefer the old backticks notation.

Linux - Solution 4:

There are three ways to do:

1) Functions:

func (){
ls -l
}
click below button to copy the code. By - Linux tutorial - team

2) Another suitable solution could be eval:

var="ls -l"
eval $var
click below button to copy the code. By - Linux tutorial - team

3) Using variables directly:

var=$(ls -l)
OR
var=`ls -l`
click below button to copy the code. By - Linux tutorial - team

You can get output of third solution in good way:

echo "$var"
click below button to copy the code. By - Linux tutorial - team

and also in nasty way:

echo $var
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

MOREF=$(sudo run command against $VAR1 | grep name | cut -c7-)
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - How to set a variable to the output from a command in Bash ?