I ran into this interesting issue while populating my WM bar with info text, which is applied by setting the root window's title, i.e. xsetroot -name "clever words"

To this end, printing a fortune works fine in a terminal:

fortune -s | while read -r; do xsetroot -name "$REPLY"; done

Yet that same fails when run from a shell script:

cat /tmp/afile | while read; do echo "$REPLY"; done


$ sh afilereader
afilereader: 2: read: arg count

Of course this is remedied by assigning our fortune result to a variable, then using xsetroot with said variable. But I'd still like to understand why this does not work in a script.

I realize each command on either side of the pipeline is run within it's own subshell, but fail to see how their localized variables could affect the while read loop. Or are variables out of scope even between the loop iterations?

What am I missing?

Update: The sh I used is linked to dash, which is in the process of being made POSIX compliant. Using the more venerable bash solved this.


You appear to be running the first example in bash, and the second in whatever is pointed to by /bin/sh, which is a POSIX shell requiring an argument to be passed specifying the variable you wish to put the input into. Changing the shebang to #!/bin/bash should fix this.

  • Good observation @Chris! That works. Think I will read up a bit on the difference between sh and bash. – invert Nov 12 '12 at 18:32
  • Abnormal indeed! I could relink /bin/sh to bash, but think I'd just use bash directly from now on, to avoid ambiguity. Thanks :) – invert Nov 12 '12 at 18:46
  • Frequently interactive shells differ from shell scripts in the buffering of their output. Reading from inter-process pipes can result in all sorts of weird timing behaviors if the command generating output buffers its writes when run non-interactively. – JesseM May 25 '17 at 22:51

In sh syntax, you need

IFS= read -r REPLY

Some shells like ksh, bash and zsh allow read to be called without a variable name but the behavior differs between them. See for instance the output of

printf 'te\ st\\\na ' | "$shell" -c 'read; printf "%s\n" "<$REPLY>"'

differing on all of bash, zsh, pdksh and ksh93

  • That makes sense why the shell I was using didn't know the variable name, thanks @Stephane. – invert Nov 12 '12 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.