Bash readline 在 while 循环中不工作
Bash readline not working inside a while loop
有一天我试过了,但我还是不明白为什么?
echo 工作正常但如果总是 return false.
#!/bin/sh -e
scan_fileExists(){
while read file; do
echo $file #echo is working
if [ -f $file ]; then
echo "Yes"
fi
done <
}
scan_fileExists "/home/myfile"
试试这个:
#!/bin/bash -e # modified
scan_fileExists(){
x=$'\r' # added
while read file; do
echo $file #echo is working
if [ -f ${file%${x}*} ]; then # modified
echo "Yes"
fi
done <
}
scan_fileExists "/home/myfile"
将 sh
保持为 shell 的其他方法(缺点:在子 shell 中作为管道成员运行时):
#!/bin/sh -e
scan_fileExists(){
tr -d "\r" < | while read file; do # modified
echo $file #echo is working
if [ -f $file ]; then
echo "Yes"
fi
done # modified
}
scan_fileExists "/home/myfile"
有一天我试过了,但我还是不明白为什么? echo 工作正常但如果总是 return false.
#!/bin/sh -e
scan_fileExists(){
while read file; do
echo $file #echo is working
if [ -f $file ]; then
echo "Yes"
fi
done <
}
scan_fileExists "/home/myfile"
试试这个:
#!/bin/bash -e # modified
scan_fileExists(){
x=$'\r' # added
while read file; do
echo $file #echo is working
if [ -f ${file%${x}*} ]; then # modified
echo "Yes"
fi
done <
}
scan_fileExists "/home/myfile"
将 sh
保持为 shell 的其他方法(缺点:在子 shell 中作为管道成员运行时):
#!/bin/sh -e
scan_fileExists(){
tr -d "\r" < | while read file; do # modified
echo $file #echo is working
if [ -f $file ]; then
echo "Yes"
fi
done # modified
}
scan_fileExists "/home/myfile"