Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl's diamond operator: can it be done in bash?

Is there an idiomatic way to simulate Perl's diamond operator in bash? With the diamond operator,

script.sh | ...

reads stdin for its input and

script.sh file1 file2 | ...

reads file1 and file2 for its input.

One other constraint is that I want to use the stdin in script.sh for something else other than input to my own script. The below code does what I want for the file1 file2 ... case above, but not for data provided on stdin.

command - $@ <<EOF
some_code_for_first_argument_of_command_here
EOF

I'd prefer a Bash solution but any Unix shell is OK.

Edit: for clarification, here is the content of script.sh:

#!/bin/bash
command - $@ <<EOF
some_code_for_first_argument_of_command_here
EOF

I want this to work the way the diamond operator would work in Perl, but it only handles filenames-as-arguments right now.

Edit 2: I can't do anything that goes

cat XXX | command

because the stdin for command is not the user's data. The stdin for command is my data in the here-doc. I would like the user data to come in on the stdin of my script, but it can't be the stdin of the call to command inside my script.

like image 590
Steven Huwig Avatar asked Dec 09 '22 21:12

Steven Huwig


2 Answers

Sure, this is totally doable:

#!/bin/bash
cat $@ | some_command_goes_here

Users can then call your script with no arguments (or '-') to read from stdin, or multiple files, all of which will be read.

If you want to process the contents of those files (say, line-by-line), you could do something like this:

for line in $(cat $@); do
    echo "I read: $line"
done

Edit: Changed $* to $@ to handle spaces in filenames, thanks to a helpful comment.

like image 81
Don Werve Avatar answered Dec 29 '22 16:12

Don Werve


Kind of cheezy, but how about

cat file1 file2 | script.sh
like image 44
Paul Tomblin Avatar answered Dec 29 '22 15:12

Paul Tomblin