有一天我试过了,但还是不明白为什么?
echo工作正常,但if总是返回false。
#!/bin/sh -e
scan_fileExists(){
while read file; do
echo $file #echo is working
if [ -f $file ]; then
echo "Yes"
fi
done < $1
}
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 < $1
}
scan_fileExists "/home/myfile"
将
sh
保留为shell的其他方法(缺点:在子shell中作为管道成员运行时):#!/bin/sh -e
scan_fileExists(){
tr -d "\r" < $1 | while read file; do # modified
echo $file #echo is working
if [ -f $file ]; then
echo "Yes"
fi
done # modified
}
scan_fileExists "/home/myfile"
关于linux - Bash readline在while循环中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29225528/