
간단히 말해서 기능이 있습니다. 아래에는 "months_and_days"라고 합니다. 그 목적은 하루에 24개의 로그를 생성하여 "연-월" 디렉터리에 저장하는 것입니다.
아래에는 "main"이라는 두 번째 함수가 있습니다. 12개월 동안 간단한 for 루프를 기반으로 디렉터리를 생성합니다. 기본 함수는 해당 디렉터리를 생성한 후 "months_and_days" 함수를 호출하여 더미 로그 파일로 채웁니다.
어떤 이유로 첫 번째 달의 디렉터리 "2018-01"만 생성하고 채운 다음 중지됩니다.
이전에는 bash에서 스크립트를 작성해 본 적이 없어서 왜 Month_and_days가 끝난 후 루프를 완료하기 위해 기본 함수로 돌아가지 않는지 잘 모르겠습니다.
메인 함수를 다시 호출하고 메인 루프에 대한 전역 변수를 유지해야 합니까?
아래 코드:
months=12
testDir=/home/name/bashScripts/testDir
fileToCopyPath=/opt/logs/192.168.217.129/2019-11/1-192.168.217.129-2019-11-24-13.log
currentMonth=0
function months_and_days () {
declare -a daysArr=(31 28 31 30 31 30 31 31 30 31 30 31)
for ((i=1; i<=${daysArr[$1]}; i++))
do
for ((j=0; j<=23; j++ ))
do
if [ $j -le 9 ]
then
tar -czvf $testDir/2018-$currentMonth/1-192-168-217-129-2018-$currentMonth-$i-0$j.tar.gz $fileToCopyPath
else
tar -czvf $testDir/2018-$currentMonth/1-192-168-217-129-2018-$currentMonth-$i-$j.tar.gz $fileToCopyPath
fi
done
done
}
function main () {
for ((i=1; i<=$months; i++))
do
if [ $i -le 9 ]
then
mkdir $testDir/2018-0$i
chmod 775 $testDir/2018-0$i
currentMonth=0$i
months_and_days "$i-1"
else
mkdir $testDir/2018-$i
chmod 775 $testDir/2018-$i
currentMonth=$i
months_and_days "$i-1"
fi
done
}
main
답변1
i
main
및 함수 모두에서 변경되는 전역 변수입니다 months_and_days
. 따라서 Months_and_days에 대한 첫 번째 호출 후 i 값은 32(jan의 일 수보다 1 더 많음)이므로 $months보다 크므로 작업이 중지됩니다.
을 추가하다
local i
이를 수정하려면 Month_and_days의 첫 번째 줄로 사용하세요.