2

For example, I have

./run.sh < file.dat

How do I get the argument "file.dat" in run.sh?

Fei
  • 117
  • 2
  • 7
  • 2
    What follows the `<` is not an argument to `./run.sh`. The contents of `file.dat` are streamed into the command by bash (or whatever shell you use), and the command never knows about it. – harpo Apr 27 '14 at 04:44
  • You don't. `bash` has already attached that file to `stdin` –  Apr 27 '14 at 04:44
  • @harpo, I think he wants to know whether there's a way to grab it anyways. :) – merlin2011 Apr 27 '14 at 04:44
  • Do you want the name, or are the file's contents really what matter? If you want the file's contents, just read from stdin the usual way. Also, what should happen if input isn't redirected, or if it comes from a pipe? – user2357112 Apr 27 '14 at 04:50
  • @user2357112 I just want the name but not the content, since I need to pass it to other java/python/C program in bash script. – Fei Apr 27 '14 at 14:38
  • 1
    @Fei: It sounds like you should be taking this input as an actual argument, rather than by redirecting stdin. – user2357112 Apr 27 '14 at 15:04
  • @user2357112 I hope I could, but the project requirement is to use strict "./run.sh < file.dat" form. – Fei Apr 27 '14 at 17:08
  • possible duplicate of [Getting Filename from file descriptor in C](http://stackoverflow.com/questions/1188757/getting-filename-from-file-descriptor-in-c) – tripleee Apr 28 '14 at 03:47

1 Answers1

4

On Linux, you can get this data from /proc:

#!/bin/bash
readlink /proc/$$/fd/0

This will print the path of whatever's opened as stdin, such as file.dat in your example.

Note that getting the filename this way is not the correct way of working with the file, and should be used purely for debugging and informational purposes.

To work with the data you should instead simply read from stdin. For example, read lines with IFS= read -r myline; echo "$myline" to read a single line, or mydata=$(cat); echo "$mydata" to read all of it.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • +1; handy to know. Caveat: On some Linux flavors - e.g., Ubuntu 12.04 - `realpath` is an `alias`, not an executable, so unless you take steps to make that alias available in your script, this won't work. On said platform the alias is defined as `alias realpath='python -c '\''import os, sys; print os.path.realpath(sys.argv[1])'\'''`. – mklement0 Apr 27 '14 at 05:22
  • @gniourf_gniourf Excellent pointer, thanks. AFAIK (I do not know for sure), all Linux flavors have a `readlink` utility, so `readlink /dev/fd/0` is the more portable choice. – mklement0 Apr 28 '14 at 04:24