1

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 ?

4
  • 2
    It's not an argument, it's not something your script has access to, it's a feature of the shell your script is running in. Commented Sep 2, 2014 at 12:13
  • How can you get anything in your output? test.sh != test Commented Sep 2, 2014 at 12:15
  • I forgot to put my debug echo before the if Commented Sep 2, 2014 at 12:17
  • Maybe you shouldn't do that at all? Why are you doing this? Commented Sep 2, 2014 at 18:33

2 Answers 2

4

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 :)

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

Comments

3

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.

1 Comment

A really good solution indeed! I would add that for Windows one might probably use handle instead of Unix-specific lsof.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.