uldics
uldics

Reputation: 134

How to detect in bash script where stdout and stderr logs go?

I have a bash script called from cron multiple times with different parameters and redirecting their outputs to different logs approximately like this:

* * * * * /home/bob/bin/somescript.sh someparameters >> /home/bob/log/param1.log 2>&1

I need my script get in some variable the value "/home/bob/log/param1.log" in this case. It could as well have a date calculated for logfilename instead of "param1". Main reason as of now is reuse of same script for similar purposes and be able to inform a user via monitored folder where he should look for more info - give him a logfile name in some warning file.

How do I detect to which log the output (&1 or both &1 and &2) goes?

Upvotes: 0

Views: 662

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19335

at runtime /usr/bin/lsof or /usr/sbin/lsof gives open file

lsof -p $$ -a -d 1

lsof -p $$ -a -d 2


filename1=$(lsof -p $$ -a -d 1 -F n)
filename1=${filename1#*$'\n'n}

filename2=$(lsof -p $$ -a -d 2 -F n)
filename2=${filename2#*$'\n'n}

Upvotes: 0

ceving
ceving

Reputation: 23871

If you are running Linux, you can read the information from the proc file system. Assume you have the following program in stdout.sh.

#! /bin/bash
readlink -f /proc/$$/fd/1 >&2

Interactively it shows your terminal.

$ ./stdout.sh 
/dev/pts/0

And with a redirection it shows the destination.

$ ./stdout.sh > nix
/home/ceving/nix

Upvotes: 3

Related Questions