5

I have a test.sh file which awks through a text file test.bed:

1   31  431
1   14  1234
1   54  134
2   435 314
2   314 414

with

while read line;do
    echo $line  
    # ... more code ... #
done < <(awk -F '\t' '$1 == 1 {print $0}' test.bed )

Running this with bash test.sh works, but with sh test.sh it gives syntax errors. How could I do the above using sh instead of bash?


The error that it gives is

test.sh: line 5: syntax error near unexpected token `<'
test.sh: line 5: `done < <(awk -F '\t' '$1 == 1 {print $0}' test.bed )'
Niek de Klein
  • 8,524
  • 20
  • 72
  • 143
  • What is the error? – vidit Apr 22 '16 at 12:17
  • @vidit test.sh: line 5: syntax error near unexpected token `<' test.sh: line 5: `done < <(awk -F '\t' '$1 == 1 {print $0}' test.bed )' – Niek de Klein Apr 22 '16 at 12:17
  • which env you're using? I didn't experienced this kind of error. Could you please paste your complete script? – ClaudioM Apr 22 '16 at 12:21
  • `<( ... )` is not valid syntax for `sh` (or `bash` in `sh` compatibility mode). – twalberg Apr 22 '16 at 16:11
  • Read [why-is-using-a-shell-loop-to-process-text-considered-bad-practice](http://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice) and you'll probably rethink your design. – Ed Morton Apr 22 '16 at 19:30

1 Answers1

13

Process Substitution is a bash extension - not specified by POSIX. This is sh compatible..

#!/bin/sh

awk -F '\t' '$1 == 1 {print $0}' test.bed  | while read line; do
echo $line
    # ... more code ... #
done
vidit
  • 6,293
  • 3
  • 32
  • 50
  • That is riddled with bugs which will bite you given various combinations of contents of test.bed, the directory you run the tool from, environment settings, etc. It also has redundant awk code but that's less important. **IF** a shell loop like this were necessary then the way to write it would be `awk -F '\t' '$1 == 1' test.bed | while IFS= read -r line; do echo "$line"; done`. Use `printf` instead of `echo` if your shell supports it for additional robustness. – Ed Morton Apr 22 '16 at 19:31
  • No, I said the approach is wrong and even if the approach was right your answer would still be the wrong way to implement it. See my first comment. – Ed Morton Apr 23 '16 at 14:09
  • The original script would work if it started with `#!/bin/bash`. I try to avoid bashisms, in scripts but there's no reason the original poster has to. – Eric Aug 19 '16 at 06:37