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!


It seems quite straightforward.

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

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).


I prefer the solution offered by Rmano's answer, but if you want to use only redirection:

read size < <(ls -l /var/spool | wc -c)
  • 1
    The main benefit of using only redirection is that it doesn't swallow errors (depending on how you have your script set up for pipe processing - set -e, set -o pipefail, etc.). So if you use $(…) your script will always continue, whereas with redirection it can be set up to fail. (which may be what you want, or not). – Garrett Motzner Dec 27 '18 at 21:26

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.