Save output in variable? [duplicate]

2019-06-28 01:43发布

问题:

This question already has an answer here:

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

How would I go about saving an output in a vaiable. For example, if I enter:

ls -l

it will show the files. How would I go about saving the output in a variable? Is it possible at all?

回答1:

You can do the following: var1=$(ls -l)



回答2:

I know three ways to do:

1) Functions are suitable for such tasks:

func (){
ls -l
}

Invoke it by saying func

2) Also another suitable solution could be eval:

var="ls -l"
eval $var

3) The third one is using variables directly:

var=$(ls -l)
OR
var=`ls -l`

you can get output of third solution in good way:

echo "$var"

and also in nasty way:

echo $var


标签: bash shell