我知道我的後續任務可以使用更簡單的「查找」註釋來完成,但我試圖使用遞歸調用來實現解決方案。我正在查看一個特定的目錄,並試圖在所有子目錄中獲得最大長度的任何文件名。但是,我的遞歸只有一個級別,所以它基本上會返回給我一個特定目錄或其子目錄中最長的文件名。遞歸bash函數(目錄迭代器)
#! /bin/bash
export maxlen=0
findmaxr()
{
if [ $# -eq 0 ] ; then
echo "Please pass arguments. Usage: findmax dir"
exit -1
fi
if [ ! -d "$1" ]; then
echo "No such directory exist."
exit -2
fi
for file in $(/bin/ls $1)
do
if [ -d "$file" ] ; then
findmaxr $file # Recursively call the method for subdirectories
else
cur=${#file}
if [ $maxlen -lt $cur ] ; then
maxlen=$cur
fi
fi
done
echo "The file with the longest name has [$maxlen] characters."
}
findmaxr `pwd`
謝謝。我在其他地方讀到解析ls有問題,但找不到解釋。您提供的信息非常有用! – DR29