Ubuntu – Redirecting output to a variable

bashcommand lineredirect

I'm interesting in directing the output from two commands to a variable. I don't want the output to be displayed on the screen, but instead assigned to a variable within my script so that I can use it again.

what I am doing is getting the file size from a directory using the commands seen below:

ls -l /var/spool | wc -c

This command gets me the file size in bytes and displays the output as an integer. I am interested in getting this integer assigned to a variable of my liking so that I can compare it against another variable later

This doesn't seem to work:

size = ls -l /var/spool | wc -c

Would redirection work?

Like this….

ls -l /var/spool | wc -c > size

Either way I want this numeric output to be assigned to a variable and not displayed on the screen.

Any suggestions are very welcomed!

Best Answer

It seems quite straightforward.

romano@RRyS:~$ size=$(ls -l /var/spool | wc -c)
romano@RRyS:~$ echo $size
476

The shell syntax $(command) executes command, and returns the standard output: just save it in a variable.

Your command:

ls -l /var/spool | wc -c > size 

will create a file named size in the current directory (containing the number and a newline).