bash – Why does cut fail with bash and not zsh?

bashhere-stringquotingwhitespacezsh

I create a file with tab-delimited fields.

echo foo$'\t'bar$'\t'baz$'\n'foo$'\t'bar$'\t'baz > input

I have the following script named zsh.sh

#!/usr/bin/env zsh
while read line; do
    <<<$line cut -f 2
done < "$1"

I test it.

$ ./zsh.sh input
bar
bar

This works fine. However, when I change the first line to invoke bash instead, it fails.

$ ./bash.sh input
foo bar baz
foo bar baz

Why does this fail with bash and work with zsh?

Additional troubleshooting

  • Using direct paths in the shebang instead of env produces the same behaviour.
  • Piping with echo instead of using the here-string <<<$line also produces the same behaviour. i.e. echo $line | cut -f 2.
  • Using awk instead of cut works for both shells. i.e. <<<$line awk '{print $2}'.

Best Answer

What happens is that bash replaces the tabs with spaces. You can avoid this problem by saying "$line" instead, or by explicitly cutting on spaces.