Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script global redirection with exec and write to screen

Tags:

bash

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?

like image 714
user2660278 Avatar asked Aug 07 '13 10:08

user2660278


People also ask

How do I redirect output to a file in bash?

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.

What does $@ do in bash script?

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.

What is &1 in shell script?

&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.


2 Answers

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"
like image 94
choroba Avatar answered Sep 29 '22 08:09

choroba


Redirect to /dev/tty, which is the controlling terminal. Works also for input.

like image 21
Tassos Bassoukos Avatar answered Sep 29 '22 07:09

Tassos Bassoukos