linux - 验证文件是否已创建 shell

标签 linux bash file shell directory

我必须编写一个 shell 脚本来监视命令中给出的一些文件夹,并在其中创建某个文件时给出消息(将从键盘读取文件名)。

谁能告诉我为什么这不起作用?

#!/bin/sh
f=`read filename`
isIn=0
for dir in $*
do
    if [ ! -d $dir ]
    then
        echo $dir is not a directory.
    fi
    for i in `find $dir -type f`
    do
        if [ $f=$i ]
        then
            echo The file $f already exists.
            isIn=1
            break
        fi
    done
    if [ $isIn -eq 0 ]
    then
        sleep 20
        isIn=0
        for i in `find $dir -type f`
        do
            if [ $f=$i ]
            then
                echo The file was created\!
                isIn=1
                break
            fi
        done
    fi
    if [ $isIn -eq 0 ]
    then
        echo The file was not created\!
    fi
done

我使用的想法是我从目录中取出所有文件并验证该文件是否不存在。 如果是 - 显示消息并移动到下一个目录。 如果没有,那么我“等待”。如果在我等待创建某个文件的时候,它会出现在所有文件的列表中,我会检查它。

我的问题是,无论我从键盘读取什么文件,我都会收到“文件已存在”的消息。没有告诉我文件的名称。

最佳答案

  1. f=`read filename` 替换为正确的用法 read fread -p filename: f
  2. find $dir -type f 打印完整的文件名,包括目录路径。由于您只需要基本名称,因此替换这两行

        for i in `find $dir -type f`
    

        for i in `find $dir -type f -printf '%f\n'`
    
  3. [ ] 中的每个运算符和操作数都必须是一个单独的参数。因此替换两行

            if [ $f=$i ]
    

            if [ "$f" = $i ]
    

关于linux - 验证文件是否已创建 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29152865/

相关文章:

bash - 查找两个文件之间的公共(public)行及其行号

python - 查找函数无法更新特定位置的文件 - python

c++ - 读写bin文件数据不对

使用 SoC(ARM、Xilinx)的 Linux 和 RTOS

linux - 如何更改或获取 Google Cloud 中 Linux Debian Server 的密码?

linux - 从匹配多个模式的一个文件创建新的多个文件的快速方法

bash - 匹配带有空格的字符串并替换为另一个类似的带有空格的字符串

ruby-on-rails - 我的应用无法从服务器加载一些图像

Linux:如何为保持扩展名的文件添加后缀

linux - 如何在 if block 的变量中捕获命令错误消息