Oscar
Oscar

Reputation: 231

Get output filename in Bash Script

I would like to get just the filename (with extension) of the output file I pass to my bash script:

a=$1
b=$(basename -- "$a")
echo $b #for debug
if [ "$b" == "test" ]; then
    echo $b
fi

If i type in:

./test.sh /home/oscarchase/test.sh > /home/oscarchase/test.txt

I would like to get:

test.txt

in my output file but I get:

test.sh

How can I procede to parse this first argument to get the right name ?

Upvotes: 1

Views: 2113

Answers (2)

chepner
chepner

Reputation: 532208

Finding out the name of the file that is opened on file descriptor 1 (standard output) is not something you can do directly in bash; it depends on what operating system you are using. You can use lsof and awk to do this; it doesn't rely on the proc file system, and although the exact call may vary, this command worked for both Linux and Mac OS X, so it is at least somewhat portable.

output=$( lsof -p $$ -a -d 1 -F n | awk '/^n/ {print substr($1, 2)}' )

Some explanation:

  • -p $$ selects open files for the current process
  • -d 1 selects only file descriptor 1
  • -a is use to require both -p and -d apply (the default is to show all files that match either condition
  • -F n modifies the output so that you get one line per field, prefixed with an identifier character. With this, you'll get two lines: one beginning with p and indicating the process ID, and one beginning with `n indicating the file name of the file.
  • The awk command simply selects the line starting with n and outputs the first field minus the initial n.

Upvotes: 3

user3159253
user3159253

Reputation: 17455

Try this:

 #!/bin/bash

 output=$(readlink /proc/$$/fd/1)
 echo "output is performed to \"$output\""

but please remember that this solution is system-dependent (particularly for Linux). I'm not sure that /proc filesystem has the same structure in e.g. FreeBSD and certainly this script won't work in bash for Windows.

Ahha, FreeBSD obsoleted procfs a while ago and now has a different facility called procstat. You may get an idea on how to extract the information you need from the following screenshot. I guess some awk-ing is required :)

Upvotes: 4

Related Questions