1

I am new to bash. When I run the following command:

grep "type" /root/myFile | cut-d'=' -f2

I get the following:

102
304
503
442

I want to store the contents of the first command into a variable such that the content of the variable would be the equivalent of declaring it like this:

myVariable="102 304 503 442"

I don't know how to go about this. Do I initialize myVariablewith an empty string and traverse the content of the command line-by-line and append it into myVariable with white spaces in between or is there an easier way for doing this with bash?

  • If necessary, you could substitute the new lines for spaces by piping the output to tr like so: tr '\n' ' ' – clk Jun 24 '16 at 18:37
1
myVariable=`grep "type" /root/myFile | cut-d'=' -f2`

What is between back-ticks (`) is run and the output is assigned to myVariable.

If your current output is separated by line feeds (\n), then you may want to replace them with spaces with tr such as:

myVariable=`grep "type" /root/myFile | cut-d'=' -f2`|tr '\n' ' '`

Note: Some people prefer using the $() syntax instead of back-ticks but both are useful and when I have the choice I use the back-ticks. The real advantage of having both is if you want to handle execution at two levels since the back-ticked expression will be sent to a sub-shell first and then the $() portion will be executed.

  • 1
    $(...) is easier on the eyes for command substitution. Easier to get the markup right with, too ;-) – Kusalananda Jun 24 '16 at 18:36
2

You can do that with bash itself, using command substitution and then parameter expansion.

First take the output of the command in a variable by using command substitution $(), and then use parameter expansion to replace all newlines with spaces ${variable//$'\n'/ }:

$ myVariable=$(grep "type" /root/myFile | cut-d'=' -f2) 
$ myVariable=${myVariable//$'\n'/ }
$ echo $myVariable
102 304 503 442

But for re-usability and cleanliness, you would be better off using an array:

myArray=( $(grep "type" /root/myFile | cut-d'=' -f2) )

and iterate over the array elements in the usual manner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.