Discussion:
[Help-bash] Why `<` has to be after `while`?
Peng Yu
2018-02-11 19:43:06 UTC
Permalink
Hi,

The following example shows that `<` has to be after `while`. But
there is no such restriction of a regulate command. Is it really
necessary to have this restriction for `while`?

$ cat main.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

tmpfile=$(mktemp -u)
seq 3 > "$tmpfile"

set -v
cat < "$tmpfile"
< "$tmpfile" cat

while read -r x
do
echo "$x"
done < "$tmpfile"

< "$tmpfile" while read -r x
do
echo "$x"
done
$ ./main.sh
cat < "$tmpfile"
1
2
3
< "$tmpfile" cat
1
2
3

while read -r x
do
echo "$x"
done < "$tmpfile"
1
2
3

< "$tmpfile" while read -r x
./main.sh: line 16: while: command not found
do
./main.sh: line 17: syntax error near unexpected token `do'
./main.sh: line 17: `do'
--
Regards,
Peng
Eric Blake
2018-02-12 14:41:38 UTC
Permalink
Post by Peng Yu
Hi,
The following example shows that `<` has to be after `while`. But
there is no such restriction of a regulate command. Is it really
necessary to have this restriction for `while`?
Yes, this matches the grammar as originally implemented by the first
'sh' more than 40 years ago, and standardized by POSIX. Shell keywords
(like 'while') are parsed differently than regular commands, and part of
that difference is that redirection operators can't precede a keyword.
--
Eric Blake, Principal Software Engineer
Red Hat, Inc. +1-919-301-3266
Virtualization: qemu.org | libvirt.org
Loading...