shell脚本,read在while循环中不起作用

时间:2014-11-15 14:48:41

标签: bash shell

我正在尝试编写一个脚本来删除那些上次修改的文件落入时间间隔...我的脚本是..

echo "enter time interval(HH:MM - HH:MM):"    
read t1    
t1=$( echo "$t1" | awk -F: '{ print ($1 * 3600) + ($2 * 60)}')    
read t2    
t2=$( echo "$t2" | awk -F: '{ print ($1 * 3600) + ($2 * 60)}')

ls -l |awk '{ print $8" "$9 }' > r    
while read line    
do   
 t=$(echo $line | awk '{print $1}' | awk -F: '{ print ($1 * 3600) + ($2 * 60)}')    
 f=$(echo $line | awk '{print $2}')         
 if [ $t -ge $t1 ]    
 then    
    if [ $t -le $t2 ]    
    then
        count=0    
        while read line1    
        do    
         if [ $count -le 10 ]    
         then    
         echo "$line1"    
         count=`expr $count + 1`    
         fi    
        done < $f    
        echo "do you want to delete this file "    
        read yn             
        case $yn in    
        'Yes' ) rm "$f";;    
        'No' ) exit;;    
    esac                
    fi    
fi    
done <r

但是读取命令(在“echo”之后你想要删除这个文件“”)是不行..... 请帮忙..

1 个答案:

答案 0 :(得分:1)

由于while,整个顶级done <r循环的输入被重定向。因此,当您尝试read yn时,它会再次显示r形式。

可能的解决方案:在进入循环之前,将标准输入重定向到其他文件描述符,并使用read -u从中读取:

#! /bin/bash
while read -u3 x ; do           # Read from the file descriptor 3.
    echo $'\t'"$x"
    if [[ $x == *echo* ]] ; then
        echo Do you see echo\?
        read y                  # True user input.
        echo Answer: "$y"
    fi
done 3< ~/file

read x                          # No redirection in effect, user input again.
# read -u3 y                    # This would cause the "Bad file descriptor" error.