Let's say I run a command in Bash like:
ls -l | grep filename
How can I save output of both command to a variable? In another words output of "ls -l" and "grep filename" to the same variable? The command must use a pipe.
Thank you in advance!
combinedOutput = ""
ls -l
total 4
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 a
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 b
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file1.txt
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file2.txt
-rw-r--r-- 1 webmaster webmaster 5 Nov 16 20:34 main.sh
ls -l | grep main.sh
-rw-r--r-- 1 webmaster webmaster 20 Nov 16 20:35 main.sh
echo $combinedOutput
total 4
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 a
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 b
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file1.txt
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file2.txt
-rw-r--r-- 1 webmaster webmaster 5 Nov 16 20:34 main.sh
-rw-r--r-- 1 webmaster webmaster 20 Nov 16 20:35 main.sh
UPDATE #1: A better example: let's say I am trying to archive and compress a directory using the following command:
tar cvf - /some/directory/ | pigz --verbose -1 -p 4 >compressed_archive.tgz;
The question is how to put outputs of "tar cvf - /some/directory/" and "pigz --verbose -1 -p 4 >compressed_archive.tgz" to a variable.
CodePudding user response:
Just run two commands.
combinedOutput=$(
ls -l
ls -l | grep filename
)
But anyway, you may be more comfortable with just:
one=$(ls -l)
two=$(ls -l | grep filename)
combinedOutput="$one
$two"
It's not possible to get the output you want with echo $combinedOutput
. You can do echo "$combinedOutput"
. Consider researching shell quoting. Check your scripts with shellcheck.
CodePudding user response:
Simply:
combinedOutput=$(( ls -l | tee /dev/stderr | grep filename ) 2>&1)
echo "$combinedOutput"