› Forums › Basic skills › Programming › Shell scripting (in bash) › Capturing the output printed by a program
- This topic has 3 replies, 2 voices, and was last updated 4 years, 1 month ago by Simon.
-
AuthorPosts
-
-
November 20, 2020 at 14:56 #13193
How do I capture the output printed by a program and extract just the part that I want?
-
November 20, 2020 at 15:03 #13194
Unix programs print output on one or both of two output streams called
stdout
(standard out) andstderr
(standard error). The former is meant for actual output and the latter for error messages, although programs are free to use either for any purpose.Here’s a program that prints to
stdout
for testing purposes: it’s just theecho
command:$ echo -e "the first line\nthe second line"
which will print this to
stdout
the first line the second line
Now let’s capture that and do something useful with it. We ‘pipe’ the output to the next program using “|” (pronounced “pipe”):
$ echo -e "the first line\nthe second line" | grep second
which gives
the second line
where
grep
finds the pattern of interest. Or how about cutting vertically to get a certain character range$ echo -e "the first line\nthe second line" | cut -c 5-9
which gives
first secon
Now combine them:
$ echo -e "the first line\nthe second line" | grep first | cut -c 5-9
to print only
first
-
November 21, 2020 at 10:52 #13206
That works, but now I need to capture that value so I can manipulate it. I don’t really understand how to do that in the shell?
-
November 21, 2020 at 11:15 #13210
Try this (again, I’m using
echo
just as an example of a program that produces output onstdout
– you are probably trying to capture the output of a more interesting program):$ echo -e "this is 1\nand now 2" $ echo -e "this is 1\nand now 2" | grep this $ echo -e "this is 1\nand now 2" | grep this | cut -d" " -f3
cut
cuts vertically and the above arguments say “define the delimiter as the space character, cut into fields using that delimiter, and give me the third field”To capture the output of a program, or of a pipeline of programs as we have above, we need to run it inside “backticks”. So, let’s capture the output of that pipeline of commands and store it in a shell variable called MYVAR:
$ MYVAR=`echo -e "this is 1\nand now 2" | grep this | cut -d" " -f3` $ echo The value is: ${MYVAR}
-
-
AuthorPosts
- You must be logged in to reply to this topic.