我试图通过在所有子目录中传递一个目录名来查找所有文件,这意味着这个过程是递归的
myrecursive() {
if [ -f $1 ]; then
echo $1
elif [ -d $1 ]; then
for i in $(ls $1); do
if [ -f $1 ]; then
echo $i
else
myrecursive $i
fi
done
else
echo " sorry"
fi
}
myrecursive $1然而,当我用另一个目录传递目录时,我得到了2次抱歉,我哪里错了?
发布于 2017-05-28 22:14:35
您尝试实现的目标只需使用find命令即可实现:
# will search for all files recursively in current directory
find . * -exec echo {} \;
# will search for all *.txt file recursively in current directory
find . -name "*.txt" -exec echo {} \;
# will search for all *.txt file recursively in current directory
# but depth is limited to 3
find . -name "*.txt" -max-depth 3 -exec echo {} \;有关手册,请参阅man find。How to run find -exec?
发布于 2017-05-28 22:54:28
你的代码的问题很简单。
ls命令将返回文件名列表,但它们对于递归无效。请改用globbing。下面的循环简单地用$1/*替换了$(ls)
myrecursive() {
if [ -f $1 ]; then
echo $1
elif [ -d $1 ]; then
for i in $1/*; do
if [ -f $1 ]; then
echo $i
else
myrecursive $i
fi
done
else
echo " sorry"
fi
}
myrecursive $1希望这能有所帮助
发布于 2017-05-28 23:12:41
#!/bin/bash
myrecursive() {
if [ -f "$1" ]; then
echo "$1"
elif [ -d "$1" ]; then
for i in "$1"/*; do
if [ -f "$i" ]; then #here now our file is $i
echo "$i"
else
myrecursive "$i"
fi
done
else
echo " sorry"
fi
}
myrecursive "$1"https://stackoverflow.com/questions/44228165
复制相似问题