+ 7
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:// github.com/davorpa/shell-utils/commit/230f71a9b2400acc24a7e92889b17bb8cd8b21a4#diff-6c619df767c9a45741832bd40be5d60ba2b2b2b45741832bd40bed6024ba2b1 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
4 Antworten
+ 4
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😊😀
+ 1
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 "$@"
exec "$0" "$@"
- 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 😥
+ 1
I will try this... with temporal file-descriptors
https://unix.stackexchange.com/questions/474177/how-to-redirect-stderr-in-a-variable-but-keep-stdout-in-the-console
0
Yes, that's correct bro👍😀