, ,

Unix – Redirect Command Output To A Variable In Bash

The example below shows command rediects to a variable, especially when the output spans multiple lines


#set shell command result to a variable
var=$(ab -n 100 -c 1 http://localhost/);

# print the content of the variable without - ignoring new line - new lines are not preserved here
echo $var;

#print the variable contents, preserving formatting like new line.
echo "$var";

#print command result whilst keeping new lines
echo "$(ls -l)"

Note: $() – Strips trailing newlines.

echo “$(ps ax)”

Results

1. http://stackoverflow.com/questions/8837129/shell-scripting-store-command-output-in-variable-and-preserve-formatting
2. http://stackoverflow.com/questions/613572/capturing-multiple-line-output-to-a-bash-variable


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *