As follow, I only want the command echo "this is to stdout" output to my screen instead of to the file ok.log, how can I do?
I search for the usage of exec shell command, but without result, please advice me

[root@161 tmp]# bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.

[root@161 tmp]# cat 2.sh
exec 1>ok.log
exec 2>error.log
#exist dir
ls /home/
#no exist dir
ls /etca/
#to stdout
echo "this is to stdout"
#other cmds
  • If you remove exec 1>ok.log, the stdout will be shown on the screen. – Marco Aug 2 '16 at 17:23
  • As I said above, I only want this command echo "this is to stdout" shown on my screen, so exec 1>ok.log is required – jython.li Aug 3 '16 at 2:18

You can save the original stdout to a temporary file descriptor before you redirect it. In this example I use file descriptor 3.

exec 3>&1
exec 1>ok.log
echo "This will go to ok.log"
echo "This will go to the original stdout" >&3
  • You're right, there is another way:echo "this is to stdout" > /dev/tty – jython.li Aug 3 '16 at 8:06
  • That /dev/tty method is a little bit different and not ideal. It would give surprising results if the script was run with stdout already redirected somewhere else. For example, if you ran ./script.sh >/dev/null you would be surprised to see output on the terminal. If you ran it as a cron job the output wouldn't be in the cron result email. – Tom Shaw Aug 3 '16 at 8:23
  • Thks, learned about – jython.li Aug 4 '16 at 2:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.