Piping to different commands based on exit status in bash -
trying achive like:
command | { [[ ${pipestatus[0] == 0 ]] && cmd_pipe_success || cmd_pipe_failed ; }
e.g. piping different commands, depending on exit-status.
the above exmaple didn't works, e.g.:
command_ok() { sed 's/^/ok /'; } command_no() { sed 's/^/no /'; } touch x ls -l x 2>&1 | { [[ ${pipestatus[0]} == 0 ]] && command_ok || command_no ; } rm x ls -l x 2>&1 | { [[ ${pipestatus[0]} == 0 ]] && command_ok || command_no ; }
both prints ok
, in both cases runs command_ok
.
is possible achieve run command_no
when exit-staus of ls
nonzero?
i know, possible achieve like
command_ok() { sed 's/^/ok /'; return 0; } command_no() { sed 's/^/no /'; return 0; } touch x res=$(ls -l x 2>&1) [[ $? == 0 ]] && command_ok <<<"$res" || command_no <<<"$res" rm x res=$(ls -l x 2>&1) [[ $? == 0 ]] && command_ok <<<"$res" || command_no <<<"$res"
but want avoid helper variable, nor temp files. possible?
as mentioned, there's no way without getting temp file involved: pipe needs set before original command finished running. however, doing temp file pretty easy:
tempfile=$(mktemp) if command > $tempfile; command_ok < $tempfile else command_no < $tempfile fi rm $tempfile
Comments
Post a Comment