脚本无法区分子目录和文件

问题描述 投票:0回答:1

我正在编写一个 bash 脚本来打印目录中的所有文件。如果有子目录,则展开它并打印其中的所有文件。这是我用以下代码处理的递归过程:

#!/bin/bash

#lsall -> list all the file in a directory and sub directory

print_dir_content(){
        echo -e "\nIn $1: (DIRECTORY)\n"
        for i in `ls $1`; do
                if ! [ -d $i ]; then
                        echo -e "F\t$i"
                else
                        print_dir_content $i
                fi
        done
}

if [ $# -lt 1 ]; then
       echo "Usage: $0 [DIR]"
       exit
else
        DIR="$1"
fi

if ! [ -d $DIR ]; then
        echo "Usage: $0 [DIR]"
        exit
fi

echo -e "\nIn $DIR:\n"
for i in `ls $DIR`; do
        echo "$i"
        if [ -d $i ]; then
                print_dir_content $i
        else
                echo -e "F\t$i"
        fi
done

脚本运行没有错误,子目录被视为文件,递归函数无法打印内部目录的内容。由于我是 bash 但不是编程新手,这是我面临的某种语言问题,还是一个逻辑问题?预先感谢。

bash printing directory
1个回答
0
投票
#!/bin/bash

print_dir_content()(
    echo -e "\nIn $1: (DIRECTORY)\n"
    cd "$1" || exit
    for i in *; do
        if ! [ -d "$i" ]; then
            echo -e "F\t$i"
        else
            print_dir_content "$i"
        fi
    done
)

if [ $# -lt 1 ]; then
    echo "Usage: $0 [DIR]"
    exit
else
    DIR=$1
fi

if ! [ -d "$DIR" ]; then
    echo "Usage: $0 [DIR]"
    exit
fi

print_dir_content "$DIR"
  • 您的代码会执行
    cd
    ,但
    ls
    输出不会返回完整路径 - 不存在的文件不能是目录
  • 解析
    ls
    输出被认为是不好的做法
  • 你的最终循环只是递归函数(如果你想保留不同的消息,你可以参数化
  • (
    ...
    )
    生成一个子 shell;或者你可以在函数末尾
    cd ..
  • 变量的使用通常应该加引号以避免分词
© www.soinside.com 2019 - 2024. All rights reserved.