我撰寫了一個遞回函式來遍歷目錄,當達到指定的深度時應該退出迭代。入口目錄和最大深度值都作為引數傳遞給函式。
perform_fragmented_copy() {
echo -e "perform_fragmented_copy: $1 at depth $2"
while [ "$1" ] && [ "$2" -le $n_max_depth ];
do
declare -i n_entry_size=$(du -sb $1 | awk '{print $1}')
if [ $sz_remainig_destination -gt $n_entry_size ]
then
echo -e "perform_fragmented_copy: can do the copy";
else
echo -e "perform_fragmented_copy: cannot, iterating again";
declare -i n_curr_depth=$(($2 1))
perform_fragmented_copy "$1"/* $n_curr_depth
fi
shift
done
echo -e "perform_fragmented_copy: exiting: $1 at depth $2"
}
呼叫為
sz_remainig_destination=10000
n_max_depth=5
perform_fragmented_copy $1 0
輸出是:
perform_fragmented_copy: /home/ROSS-82/ at depth 0
perform_fragmented_copy: cannot, iterating again
perform_fragmented_copy: /home/ROSS-82//82 at depth /home/ROSS-82//ross_reader-82
./ftest.sh: line 69: [: /home/ROSS-82//ross_reader-82: integer expression expected
perform_fragmented_copy: exiting: /home/ROSS-82//82 at depth /home/ROSS-82//ross_reader-82
./ftest.sh: line 69: [: : integer expression expected
perform_fragmented_copy: exiting: 0 at depth
在第一次遞回的輸出中$2接收為整數,即 0
perform_fragmented_copy: /home/ROSS-82/ at depth 0
在第二次遞回的輸出中$2接收為$1
perform_fragmented_copy: /home/ROSS-82//82 at depth /home/ROSS-82//ross_reader-82
我嘗試了很多方法來解決這個問題,并在谷歌上搜索了解決方案,但還沒有結果。
uj5u.com熱心網友回復:
您應該將深度移至第一個引數。然后,您可以將其移出回圈之前的引數串列,回圈使用 and 處理剩余的$1引數shift。
perform_fragmented_copy() {
depth=$1
shift
echo -e "perform_fragmented_copy: $@ at depth $depth"
if [ "$depth" -ge "$n_max_depth" ]
then return
fi
declare -i n_curr_depth=$(($depth 1))
while [ $# -gt 0 ];
do
declare -i n_entry_size=$(du -sb "$1" | awk '{print $1}')
if [ $sz_remainig_destination -gt $n_entry_size ]
then
echo -e "perform_fragmented_copy: can do the copy";
else
echo -e "perform_fragmented_copy: cannot, iterating again";
perform_fragmented_copy $n_curr_depth "$1"/*
fi
shift
done
echo -e "perform_fragmented_copy: exiting: at depth $depth"
}
你不能$1在最后的exiting訊息中參考,因為當所有引數都被移走時回圈結束。當$1為空時回圈結束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487325.html
下一篇:gsed用帶單引號的變數$i替換
