我正在编写一个 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 但不是编程新手,这是我面临的某种语言问题,还是一个逻辑问题?预先感谢。
#!/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 ..