파일 정보 검색 및 형식 지정
이 단계에서는 지정된 디렉토리에서 파일 및 디렉토리 정보를 검색하고 ls -lh 명령어와 동일한 방식으로 출력을 형식화하는 코드를 추가합니다. 이 단계를 완료하려면 아래 단계를 따르세요:
ls 명령어를 사용하여 지정된 디렉토리의 파일 및 디렉토리에 대한 자세한 정보를 검색하고 출력을 ls_output 변수에 저장합니다:
## Use the ls command to retrieve detailed information about files and directories, then process the output line by line
ls_output=$(ls -l --time-style="+%b %d %Y %H:%M" "$1" | tail -n +2)
ls_output의 각 줄을 처리하고 필요한 정보를 추출하기 위해 while 루프를 추가합니다:
## Process each line of the ls output
## Remove trailing whitespace from each line
## Parse each field of the line
- 파일 크기를 가독성이 좋게 형식화하는 코드를 추가합니다:
## Format the file size for better readability
if [[ $size =~ ^[0-9]+$ ]]; then
## If the size is a number, format it
if ((size < 1024)); then
size_formatted="${size}B"
elif ((size < 1024 ** 2)); then
size_formatted="$(printf "%.1f" $(echo "scale=2; $size / 1024" | bc))K"
elif ((size < 1024 ** 3)); then
size_formatted="$(printf "%.1f" $(echo "scale=2; $size / (1024**2)" | bc))M"
else
size_formatted="$(printf "%.1f" $(echo "scale=2; $size / (1024**3)" | bc))G"
fi
else
## If the size cannot be parsed as a number, keep it as is
size_formatted="$size"
fi
- 파일의 수정 시간을 기준으로 적절한 날짜 형식을 결정하는 코드를 추가합니다:
current_year=$(date +"%Y")
## Extract year, month, and day from the modified date
file_year=$(echo "$year" | cut -d' ' -f3)
file_month=$(echo "$month" | cut -d' ' -f1)
file_day=$(echo "$day" | cut -d' ' -f1)
## Convert leading zero in month to decimal format
file_month=$(echo "$file_month" | sed 's/^0//')
## Get the timestamp of the file's last modification
file_modified=$(date -d "$month $day $year" +"%s")
## Get the timestamp of 6 months ago
six_months_ago=$(date -d "6 months ago" +"%s")
## Calculate the difference in seconds between the current time and the file's last modification
time_diff=$(($(date +"%s") - file_modified))
if ((file_year == current_year)); then
## If the file's year is the same as the current year
if ((time_diff >= six_months_ago)); then
## More than 6 months ago, display the full date: Month Day Year
formatted_date="$month $day $year"
else
## Within the last 6 months, display the date and time: Month Day HH:MM
formatted_date="$month $day $time"
fi
else
## If the file's year is different from the current year, display the full date: Month Day Year
formatted_date="$month $day $year"
fi
- 마지막으로, 형식화된 파일 정보를 출력하는 코드를 추가합니다:
## Output format includes customized date formatting based on the condition
이제 완전한 newls.sh 스크립트가 준비되었습니다. 파일을 저장하고 다음 단계로 진행할 수 있습니다.