Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - Write to terminal after redirecting stdout to a file without using stderr?

I have two shell scripts, one that serves as the main "program" and another that serves as a "library."

In several places in the "program," I'll do something like: log "$thing" >> "$logfile", where log is a function defined in the "library."

# program.sh

logfile="log.txt"
stuff="hahah heheh hoho"

. library.sh 

for thing in $stuff; do
  log "$thing" >> "$logfile"
done

My question: Is there a way to redirect some of the output from the function back to the terminal without using stderr?

# library.sh

log () {

  # This gets written to the log
  echo "`date --rfc-3339=seconds`: $1"

  # How to write this to the terminal *without* using stderr?
  echo "Info: Message written to log." >&2

}

I want to avoid the use of stderr because in my actual program, there's an option to redirect errors to a file, but the messages I want to send to the terminal are informational, not errors, and should always show up on the terminal.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Open /dev/tty on another FD.

exec 0< /dev/null
exec 1> /dev/null
exec 2> /dev/null
exec 3> /dev/tty
echo 'Hello, World!' >&3 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...