I have a large bash script and I want to globally redirect all stdout/stderr to a file, except some progress indicators such specific echo messages. For example, consider the following script
#!/bin/bash
# all stdout and stderr go to out.log
exec &> out.log
special_echo "starting"
# many other commands go here
# which output both the stdout and stderr
# also some special_echo commands in here,
# for example
echo "msg1"
special_echo "middle"
echo "msg2" >&2
special_echo "finished"
When it is run the output should be
$ ./script
starting
middle
finished
$
But, out.log
should contain
msg1
msg2
How to implement special_echo
functionality? I've tried using a file descriptor and echoing to that but can't get it to display on the screen.
Is there a way to achieve this without appending redirection to every line or doing something like in this answer?
For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
&1 is used to reference the value of the file descriptor 1 (stdout). both Standard output (stdout) and Standard Error (stderr) will redirected to output.
Yes, using another file descriptor is the way to go:
#!/bin/bash
exec 3>&1
special_echo () {
echo "$@" >&3
}
exec &> out.log
special_echo "starting"
echo "msg1"
special_echo "middle"
echo "msg2" >&2
special_echo "finished"
Redirect to /dev/tty, which is the controlling terminal. Works also for input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With