检索并格式化文件信息
在这一步中,你将添加代码,从指定目录中检索文件和目录信息,并以与 ls -lh 命令相同的方式格式化输出。按照以下步骤完成此步骤:
- 使用
ls 命令检索指定目录中文件和目录的详细信息,并将输出存储在 ls_output 变量中:
## 使用 ls 命令检索文件和目录的详细信息,然后逐行处理输出
ls_output=$(ls -l --time-style="+%b %d %Y %H:%M" "$1" | tail -n +2)
- 添加一个
while 循环来处理 ls_output 的每一行,并提取必要的信息:
## 处理 ls 输出的每一行
## 去除每行末尾的空白字符
## 解析每行的每个字段
- 添加代码以格式化文件大小,使其更具可读性:
## 格式化文件大小以提高可读性
if [[ $size =~ ^[0-9]+$ ]]; then
## 如果大小是一个数字,则进行格式化
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
## 如果大小不能解析为数字,则保持原样
size_formatted="$size"
fi
- 添加代码以根据文件的修改时间确定合适的日期格式:
current_year=$(date +"%Y")
## 从修改日期中提取年、月、日
file_year=$(echo "$year" | cut -d' ' -f3)
file_month=$(echo "$month" | cut -d' ' -f1)
file_day=$(echo "$day" | cut -d' ' -f1)
## 将月份中的前导零转换为十进制格式
file_month=$(echo "$file_month" | sed 's/^0//')
## 获取文件最后修改的时间戳
file_modified=$(date -d "$month $day $year" +"%s")
## 获取六个月前的时间戳
six_months_ago=$(date -d "6 months ago" +"%s")
## 计算当前时间与文件最后修改时间之间的秒数差
time_diff=$(($(date +"%s") - file_modified))
if ((file_year == current_year)); then
## 如果文件的年份与当前年份相同
if ((time_diff >= six_months_ago)); then
## 超过六个月前,显示完整日期:月 日 年
formatted_date="$month $day $year"
else
## 在过去六个月内,显示日期和时间:月 日 HH:MM
formatted_date="$month $day $time"
fi
else
## 如果文件的年份与当前年份不同,显示完整日期:月 日 年
formatted_date="$month $day $year"
fi
- 最后,添加代码以输出格式化后的文件信息:
## 输出格式包括根据条件定制的日期格式化
完整的 newls.sh 脚本现在已准备好。你可以保存文件并继续下一步。