Pipe bash stdout only in "debug" mode
I'm trying to achieve this:
PIPE=""
if [ $DEBUG = "true" ]; then
PIPE="2> /dev/null"
fi
git submodule init $PIPE
But $PIPE
gets interpreted as command line args to git. How can I show stdout
and stderr
only in debug mode, while piping only stderr
in non-debug mode?
Thanks for great insights. Ended up with doing this, which redirects everything to /dev/null if not in debug mode, and prints both stderr and stdout when in debug mode:
# debug mode
if [[ ${DEBUG} = true ]]; then
PIPE=/dev/stdout
else
PIPE=/dev/null
fi
git submodule init 2>"${PIPE}" 1>"${PIPE}"
Using variable after >
if [[ ${DEBUG} = true ]]; then
errfile=/dev/stderr
else
errfile=/dev/null
fi
command 2>"${errfile}"
Modifying file descriptors
You can duplicate the stderr to new file descriptor 3
if [[ ${DEBUG} = true ]]; then
exec 3>&2
else
exec 3>/dev/null
fi
then for each command you want to use new redirection
command 2>&3
To close fd 3, if no longer needed
exec 3>&-
First i guess you logic is going the wrong way, with DEBUG=true you would be sending stderr to /dev/null. Furthermore your string comparsion is missing the second "=",
How about the simple solution?
if [ "${DEBUG}" == "true" ]; then
git submodule init
else
git submodule init 2>/dev/null
fi
Edit upon your reply:
Alternatively you could use eval
, but be careful it's considered evil ;)
if [ "${DEBUG}" == "true" ]; then
PIPE=""
else
PIPE="2>/dev/null"
fi
eval git submodule init $PIPE
链接地址: http://www.djcxy.com/p/77104.html