2

I intend to execute this way:

./some_code | ./my_bash.sh

What is the syntax in ./my_bash.sh so that it can take input from other as pipe?

I tried this but wont work.

#!/bin/bash

# this is ./my_bash.sh
cut -f1 $@ | grep 'foo' | wc -l 
# $@ failed 
neversaint
  • 60,904
  • 137
  • 310
  • 477
  • 1
    except for the `@$` part, the code you have should work. However, you could write it as `cut -f1 | grep -c 'foo'`, or even just `grep -c $'^[^\t]*foo[^\t]*'` – kojiro Jul 10 '12 at 00:10
  • See [reading values from a STDIN pipe](http://stackoverflow.com/questions/2746553/bash-script-read-values-from-stdin-pipe) – jmdeldin Jul 10 '12 at 00:12
  • @kojiro: You should post that as an answer, because it is one and deserves to be upvoted and credited as such. – Walter Mundt Jul 10 '12 at 00:13

1 Answers1

1

It's not clear what you want the arguments ($@) to do. Perhaps just remove that part. Other than that the code you have should work. However, you could write it as cut -f1 | grep -c 'foo', or even just grep -c $'^[^\t]*foo[^\t]*'.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • To explain: basically, `cut` reads from standard input by default. In your pipe-target script, the standard input of `cut` is the standard input of your script, which in turn is coming from the pipe, so that should work. – Walter Mundt Jul 10 '12 at 00:18
  • If you want the script to be able to take arguments for `cut` and pass them along as an additional feature, you can write it like so: `cut -f1 "$@" | grep 'foo' | wc -l`. The quotes around `$@` are magical, and in this specific usage what they do is tell bash to pass along *precisely* the arguments you got, with no re-splitting on spaces or other re-interpretations. – Walter Mundt Jul 10 '12 at 00:20