The question is published on by Tutorial Guruji team.
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 myVariable
with 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?
Answer
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.