Linux 파일 목록 사용자 정의

LinuxBeginner
지금 연습하기

소개

이 프로젝트에서는 사용자 친화적인 형식으로 디렉토리 크기를 표시하는 사용자 정의 ls 명령어를 만드는 방법을 배우게 됩니다. 이 프로젝트는 Zsh 스크립팅을 사용하여 Linux 환경에서 파일 정보를 검색하고 형식화하는 방법을 이해하는 데 도움이 될 것입니다.

👀 미리보기

$ sh newls.sh /home/labex
## 예시
drwxr-xr-x 1 labex 6B Oct 13 10:11 Code
drwxr-xr-x 1 labex 120B Oct 13 10:11 Desktop
drwxr-xr-x 1 labex 28B Sep 23 2021 golang
drwxr-xr-x 1 labex 22B Oct 23 10:17 project

🎯 과제

이 프로젝트에서 다음을 배우게 됩니다:

  • 파일 및 디렉토리 정보를 표시하는 Zsh 스크립트를 만드는 방법
  • 파일 크기를 가독성이 좋게 형식화하는 방법
  • 파일 수정 시간에 적합한 날짜 형식을 결정하는 방법
  • ls -lh 명령어와 동일한 형식으로 파일 정보를 출력하는 방법

🏆 성과

이 프로젝트를 완료하면 다음을 수행할 수 있습니다:

  • 지정된 디렉토리의 파일 및 디렉토리 크기를 표시할 수 있는 Zsh 스크립트 작성
  • 파일 크기 정보를 가독성이 좋게 형식화
  • 현재 연도와 파일의 마지막 수정 시간을 기준으로 파일 수정 시간에 적합한 날짜 형식 결정
  • ls -lh 명령어와 일치하는 사용자 친화적인 형식으로 파일 정보 출력

newls.sh 스크립트 생성

이 단계에서는 지정된 디렉토리의 모든 파일과 디렉토리의 크기를 표시하는 newls.sh 스크립트를 생성합니다. 이 단계를 완료하려면 아래 단계를 따르세요:

  1. 텍스트 편집기를 열고 /home/labex/project 디렉토리에 newls.sh라는 새 파일을 만듭니다.
  2. 이 파일이 Zsh 스크립트임을 지정하기 위해 파일 시작 부분에 다음 shebang 라인을 추가합니다:
#!/bin/zsh
  1. 스크립트의 목적을 설명하기 위해 스크립트 시작 부분에 주석 블록을 추가합니다:
## This script retrieves and formats file information from a specified directory, displaying it in the same format as the "ls -lh" command.
  1. 이제 입력 매개변수 (목록을 표시할 디렉토리) 가 제공되었는지 확인하는 코드를 추가합니다. 그렇지 않은 경우 사용법 메시지를 표시하고 스크립트를 종료합니다:
## Check if the input parameter is empty
if [ $## -eq 0 ]; then
  echo "Usage: sh newls.sh <directory>"
  exit 1
fi
  1. 다음으로, 지정된 디렉토리가 존재하는지 확인하는 코드를 추가합니다. 그렇지 않은 경우 오류 메시지를 표시하고 스크립트를 종료합니다:
## Check if the directory exists
if [ ! -d "$1" ]; then
  echo "Directory $1 does not exist."
  exit 1
fi
✨ 솔루션 확인 및 연습

파일 정보 검색 및 형식 지정

이 단계에서는 지정된 디렉토리에서 파일 및 디렉토리 정보를 검색하고 ls -lh 명령어와 동일한 방식으로 출력을 형식화하는 코드를 추가합니다. 이 단계를 완료하려면 아래 단계를 따르세요:

  1. 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)
  1. ls_output의 각 줄을 처리하고 필요한 정보를 추출하기 위해 while 루프를 추가합니다:
## Process each line of the ls output
## Remove trailing whitespace from each line

## Parse each field of the line
  1. 파일 크기를 가독성이 좋게 형식화하는 코드를 추가합니다:
## 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
  1. 파일의 수정 시간을 기준으로 적절한 날짜 형식을 결정하는 코드를 추가합니다:
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
  1. 마지막으로, 형식화된 파일 정보를 출력하는 코드를 추가합니다:
## Output format includes customized date formatting based on the condition

이제 완전한 newls.sh 스크립트가 준비되었습니다. 파일을 저장하고 다음 단계로 진행할 수 있습니다.

✨ 솔루션 확인 및 연습

newls.sh 스크립트 테스트

이 단계에서는 newls.sh 스크립트가 예상대로 작동하는지 확인하기 위해 테스트합니다. 이 단계를 완료하려면 아래 단계를 따르세요:

  1. 터미널을 열고 /home/labex/project 디렉토리로 이동합니다.
  2. /home/labex 디렉토리를 인수로 사용하여 newls.sh 스크립트를 실행합니다:
sh newls.sh /home/labex
  1. 출력 결과가 챌린지 설명에 표시된 예상 형식과 일치하는지 확인합니다:
drwxr-xr-x 1 labex 6B Oct 13 10:11 Code
drwxr-xr-x 1 labex 120B Oct 13 10:11 Desktop
drwxr-xr-x 1 labex 28B Sep 23 2021 golang
drwxr-xr-x 1 labex 22B Oct 23 10:17 project
  1. 출력 결과가 예상 형식과 일치하면 newls.sh 스크립트가 올바르게 작동하는 것입니다. 그렇지 않은 경우 스크립트를 검토하고 필요한 수정을 수행합니다.

축하합니다! 프로젝트를 성공적으로 완료했으며 디렉토리 크기를 사용자 친화적인 형식으로 표시하는 사용자 정의 ls 명령어를 만들었습니다.

✨ 솔루션 확인 및 연습

요약

축하합니다! 이 프로젝트를 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.