0

I'm new to bash programming and struggling with this one portion of my program. I know how to use positional parameters in order to refer to certain elements of the command line, however, I can only get this to work if a file is specified. How can I use positional parameters with standard input like so:

  cat test_file | stats -r

In this instance, I can refer to stats with "$0" and -r with "$1" but how can I refer to the cat test_file part? For context, Stats is my program which finds the average and median of the numbers in test file. "-r' indicates that the program should read each row of the program. When the command line is written like this:

 stats -r test_file

I use this code to denote the -r

 if [[ "${1:0:2}" == '-r' ]]
     do stuff  
user2466886
  • 205
  • 1
  • 3
  • 14
  • 1
    _but how can I refer to the `cat test_file` part?_ Short answer: You can't! – gniourf_gniourf Oct 11 '15 at 15:42
  • If there is no positional argument (which you can tell by looking at `$#`), then you should just read from stdin. That will work with pipes as well as the case where the user wishes to type directly into the program. – rici Oct 11 '15 at 15:48
  • How could I read from standard input if I needed to use it as an argument for a function ? So with the positional parameters i call the function like this: rows_stats $2 where $2 refers to the file name. How can I do the same with just standard input? – user2466886 Oct 11 '15 at 15:54
  • Oh I figured it out -- post below – user2466886 Oct 11 '15 at 15:59

2 Answers2

-1

Try this: stats -r "$(cat test_file)"

grimsock
  • 774
  • 5
  • 18
  • Yes but this is for an assignment and the graders will explicitly try using "cat test_file | stats - r " to see if the program works that way. – user2466886 Oct 11 '15 at 15:48
-1

Answer: As people stated you can't use positional parameters in this situation. The only alternative is to read from standard input and in my case store it in a variable to pass to a function.

Read here to learn more how to do that: How to read mutliline input from stdin into variable and how to print one out in shell(sh,bash)?

Community
  • 1
  • 1
user2466886
  • 205
  • 1
  • 3
  • 14
  • How does storing stdin into a variable help you pass it to a functing expecting a filename? (If you need to refer to stdin using a filename, it's `/dev/stdin`.) – rici Oct 13 '15 at 04:19