shell: How to capture stderr output depending on a flag | Sololearn: Learn to code for FREE!


shell: How to capture stderr output depending on a flag

Someone would be able to help me with the TODO in shell/bash which can be seen at https:// Is there some approach to capture the output in a local variable or with pipes and conditionally print it afterwards? I have already tried many ways like with command substitution and pipes, but the original output loses colors... escapes. With file descriptors I still do not clarify very well and I always fail. Thanks for support

9/9/2021 10:06:02 PM

David Ordás

4 Answers

New Answer


Yes, there are some ways to capture the output of a command bro. Most of extern commands output something to stdout (Standard Output). You can capture that output, for example, for example, using `` and the command inside of them. For example: output=`echo "hi to everybody"` echo "$output" Output: Hi to everybody Hope this help you, if you're still facing problems, you can DM me, and I will help you๐Ÿ˜Š๐Ÿ˜€


I've read a lot about theory but not fresh with practice and always failing - normal local ecode; ( my-cmd "arg" ) && ecode=$? || ecode=$? - command substitution. $() or legacy `` local output; output=$(my-cmd "arg") local ecode=$? echo -e "$ecode $output" printf '%s %s\n' "$ecode" "$output" - raw eval / exec eval "[email protected]" exec "$0" "[email protected]" - redirect file descriptors: my-cmd "arg" 2>/dev/null #ignore stderr my-cmd "arg" >> file.txt #append all 2 file - temp fds: ๐Ÿ˜– { var="$( { my-cmd; } 2>&1 1>&3 3>&- )"; } 3>&1; - pipes my-cmd "arg" | tee ... - descriptor context exec (๐Ÿ˜ฒbashismo) local var; my-cmd "arg" 2> >( read var <<<&1 ) three first is the unique I know use more or less fine. With command substitution I see in my terminal that colors send by original command are lost. it's rare because new lines don't. with pipes I lost exit code of my-cmd I misunderstand the others: syntax, advantages/disadvantages too much to learn ๐Ÿ˜ฅ


I will try this... with temporal file-descriptors


Yes, that's correct bro๐Ÿ‘๐Ÿ˜€