3

I'd like to write a bash script myscript such that issuing this command:

myscript > filename.txt

would return the name of the filename that it's output is being redirected to, filename.txt. Is this possible?

1
  • 1
    No, the script does not have access to that information. Commented Aug 24, 2012 at 16:32

2 Answers 2

1

If you are running on Linux, check where /proc/self/fd/1 links to.

For example, the script can do the following:

#!/bin/bash
readlink /proc/self/fd/1

And then run it:

$ ./myscript > filename.txt
$ cat filename.txt
/tmp/filename.txt

Note that if you want to save the value of the output file to a variable or something, you can't use /proc/self since it will be different in the subshell, but you can still use $$:

outputfile=$(readlink /proc/$$/fd/1)
Sign up to request clarification or add additional context in comments.

1 Comment

I'm guessing this would be a bit faster than the lsof approach since it doesn't have to spawn awk.
1

Using lsof:

outfile=$(lsof -p $$ | awk '/1w/{print $NF}')
echo $outfile

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.