1

I have a shell script which does echo for some important places in the logic. Every time I do an echo I apeend the log to a log file by doing a >> /some/location/my_logtxt.

The logic looks like below

ret=123 echo Something happened $ret >> /some/location/my_logtxt // some logic echo Something else happened $ret >> /some/location/my_logtxt // some more logic echo Something else happened again $ret >> /some/location/my_logtxt 

Question:
Isnt there a single statement which can state all the echo statement logs go into the following file instead of doing this >> /some/location/my_logtxt for every echo?

2
  • What are you trying to save here? reduce the number of lines? Probably define a function and pass the argument as the string to write to the file and call the function with arguments? Commented Oct 10, 2018 at 9:55
  • ok . creating a method should work as well. But I wanted to know is there is a standard way in shell scripting to deal with this Commented Oct 10, 2018 at 9:58

2 Answers 2

3

If you want all output to go to the log file, you can use exec to redirect:

exec >> "$logfile" 

You might wish to redirect stderr, too: 2>&1.


If you want just your echo commands to be redirected, you can connect an unused stream (greater than 2) for that:

exec 3>> "$logfile" ret=123 echo "Something happened $ret" >&3 # some logic echo "Something else happened $ret" >&3 

Note that these approaches no longer re-open the log for every write - if you rename the log file, output will continue to go to it, whereas in the original, subsequent output would end up in a new file with the old name.

Sign up to request clarification or add additional context in comments.

Comments

2

You can scope your stuff in a subshell and redirect the subshell's output:

( ret=123 echo Something happened "$ret" // some logic echo Something else happened "$ret" // some more logic echo Something else happened again "$ret" ) >> /some/location/my_logtxt 

If you just want to affect your echo statements, I propose to use a myecho statement instead:

myecho() { echo "$@" >> /some/location/my_logtxt } ret=123 myecho Something happened "$ret" // some logic myecho Something else happened "$ret" // some more logic myecho Something else happened again "$ret" 

(A more fitting name might be something like log instead of myecho, but I guess you got the point.)

1 Comment

ah. this is also a nice technique on what I was looking for. Thanks a lot

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.