ループに対して `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

おすすめ記事