Search code examples
bashscriptinglines

Counting file lines in shell and in a script gives different results


For a bunch of files in a directory I want to get the number of lines for each one, store it in a variable and do additional stuff. Via shell I can do it without problems if I do

read NLINES <<<  $( cat file  |  wc  -l )

but if I do it in a script

#!/bin/bash
for i in `ls *.dat `
do
    read NLINES <<<  $( cat $i  |  wc  -l )
done

I get

Syntax error: redirection unexpected

Why the difference? How could I fix it?


Solution

  • I bet your default shell isn't bash but something else. Leave the #!/bin/bash and replace it with #!/bin/sh, to let your script use the default shell.

    I made this error the other way, when I tried to use some debian scripts on Ubuntu, where #!/bin/sh behaved differently from my assumed #!/bin/bash.