루프에 대해 `ls`의 모든 파일을 확인하고 조건에 따라 메시지를 표시합니다.

루프에 대해 `ls`의 모든 파일을 확인하고 조건에 따라 메시지를 표시합니다.

특정 디렉토리가 존재하는지 확인하고 존재하지 않는 경우 이를 생성하는 스크립트를 만들었습니다. 그런 다음 for 루프를 사용하여 현재 디렉터리에 있는 숨겨지지 않은 모든 일반 파일을 반복합니다. 파일이 비어 있으면 사용자에게 파일을 이동할 것인지 묻는 메시지가 표시됩니다. 제가 겪고 있는 문제는 스크립트가 파일 실행을 마친 후 모든 파일이 비어 있는지 확인한 다음 메시지를 표시해야 한다는 것입니다. 이것이 내가 가진 것입니다.

#!/bin/bash
if [ -d Empty_Files ]
then
    echo "This file directory exists already. Move on"
else
    mkdir Empty_Files
    echo "I created the Empty_Files directory since it didn't exist before"
fi

for file in `ls`
do
 if [ ! -s $file ]
  then
  echo "Would you like" $file "moved to Empty_Files? It's empty! Enter Yes or No"
 read userinput
   if [ $userinput = "Yes" ]
    then 
    mv $file ./Empty_Files
   fi
 if [ $userinput = "No" ]
  then
    echo "Ok, I will not move it!"
 fi
 fi
done
 if [ -s $file ]
   then
     echo "There are no empty files!"
     exit 55
fi

보시다시피, 제가 if마지막으로 한 말은 원하는 효과를 얻지 못했습니다.

답변1

  1. 명령 대체에 역따옴표(둘러싸기)를 사용하지 마십시오 ls. 읽기가 쉽지 않고 문제가 있습니다. 다른 명령의 출력을 사용해야 하는 경우 $(command args1 args2)대신 양식을 사용하세요.

  2. ls를 구문 분석하지 마세요. 대신 셸 와일드카드를 사용하세요.

    for file in *
    
  3. 모든 변수를 인용하세요:

    if [ ! -s "$file" ]
    
  4. exit 55매우 일반적인 유형의 오류는 아닙니다. 보통 사람들은 exit 1.

  5. 코드를 들여쓰기하여 각 부분이 수행하는 작업, 각 if 문이 시작/끝나는 위치, 각 루프가 시작되고 끝나는 위치를 명확하게 알 수 있습니다.

이것은 고정된 스크립트입니다

#!/bin/bash

if [ -d Empty_Files ]
then
    echo "This file directory exists already. Move on"
else
    mkdir Empty_Files
    echo "I created the Empty_Files directory since it didn't exist before"
fi

count=0
for file in *
do
    if [ ! -s "$file" ]
    then
        count=$(( $count+1  ))
        echo "Would you like" $file "moved to Empty_Files? It's empty! Enter Yes or No"
        read userinput

        if [ "$userinput" = "Yes" ]
        then 
            mv "$file" ./Empty_Files
        fi

        if [ "$userinput" = "No" ]
        then
            echo "Ok, I will not move it!"
        fi
fi
done

# quoting here not necessary because it's integer
if [ $count -eq 0  ];
then
     echo "There are no empty files!"
     exit 1
fi

테스트 실행

[2821][TESTDIR][11:14]:
$ tree
.
├── Empty_Files
└── move_empty.sh

1 directory, 1 file

[2821][TESTDIR][11:14]:
$ ./move_empty.sh                                                                                     
This file directory exists already. Move on
There are no empty files!

[2821][TESTDIR][11:14]:
$ touch empty1 empty2

[2821][TESTDIR][11:14]:
$ ./move_empty.sh                                                                                     
This file directory exists already. Move on
Would you like empty1 moved to Empty_Files? It's empty! Enter Yes or No
Yes
Would you like empty2 moved to Empty_Files? It's empty! Enter Yes or No
No
Ok, I will not move it!

[2821][TESTDIR][11:14]:
$ tree
.
├── empty2
├── Empty_Files
│   └── empty1
└── move_empty.sh

1 directory, 3 files

관련 정보