cat file.txt |
while read in; do
chmod 755 "$in"
done
会起作用,但有两个问题:
cat |是一个无用的叉,和
| while ... ;done将成为亚层,其环境将在;done之后消失。
所以这样写更好:
while read in; do
chmod 755 "$in"
done < file.txt
但
你可能会被警告$IFS和read标志:
help read
read: read [-r] ... [-d delim] ... [name ...]
...
Reads a single line from the standard input... The line is split
into fields as with word splitting, and the first word is assigned
to the first NAME, the second word to the second NAME, and so on...
Only the characters found in $IFS are recognized as word delimiters.
...
Options:
...
-d delim continue until the first character of DELIM is read,
rather than newline
...
-r do not allow backslashes to escape any characters
...
Exit Status:
The return code is zero, unless end-of-file is encountered...
在某些情况下,您可能需要使用
while IFS= read -r in;do
chmod 755 "$in"
done <file.txt
用来避免奇怪文件名的问题。如果你遇到UTF-8的问题:
while LANG=C IFS= read -r in ; do
chmod 755 "$in"
done <file.txt
while read <&7 filename; do
ans=
while [ -z "$ans" ]; do
read -p "Process file '$filename' (y/n)? " foo
[ "$foo" ] && [ -z "${foo#[yn]}" ] && ans=$foo || echo '??'
done
if [ "$ans" = "y" ]; then
echo Yes
echo "Processing '$filename'."
else
echo No
fi
done 7<file.txt
如果你想在更多不同的步骤中读取输入文件,你必须使用:
exec 7<file.txt # Without spaces between `7` and `<`!
# ls -l /dev/fd/
read <&7 headLine
while read <&7 filename; do
case "$filename" in
*'----' ) break ;; # break loop when line end with four dashes.
esac
....
done
read <&7 lastLine
exec 7<&- # This will close file descriptor 7.
# ls -l /dev/fd/