while循环不执行

时间:2014-04-02 13:29:02

标签: bash shell

我目前有这段代码:

listing=$(find "$PWD")
fullnames=""
while read listing;
do
    if [ -f "$listing" ]
        then
            path=`echo "$listing" | awk -F/ '{print $(NF)}'`
            fullnames="$fullnames $path"
            echo $fullnames
    fi 
done

出于某种原因,这个脚本无效,我认为这与我编写while循环/声明列表的方式有关。基本上,代码应该从find $ PWD中提取文件的实际名称,即blah.txt。

1 个答案:

答案 0 :(得分:6)

read listing未读取字符串listing中的值;它使用从标准输入读取的行设置listing的值。试试这个:

# Ignoring the possibility of file names that contain newlines
while read; do
    [[ -f $REPLY ]] || continue
    path=${REPLY##*/}
    fullnames+=( $path )
    echo "${fullnames[@]}"
done < <( find "$PWD" )

使用bash 4或更高版本,您可以使用

简化此操作
shopt -s globstar
for f in **/*; do
    [[ -f $f ]] || continue
    path+=( "$f" )
done
fullnames=${paths[@]##*/}
相关问题