检查 `ls` for 循环中的所有文件并根据条件显示消息

检查 `ls` for 循环中的所有文件并根据条件显示消息

我创建了一个脚本来检查某个目录是否存在;如果没有,则创建它。然后使用 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. 不要在命令替换中使用反引号(around ls)。它的可读性不太好并且存在问题。如果必须使用另一个命令的输出,请使用$(command args1 args2)form 代替

  2. 不解析 ls。使用 shell 通配符代替:

    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

相关内容