【问题标题】:Verify if a file was created shell验证是否创建了文件 shell
【发布时间】:2015-05-23 01:20:19
【问题描述】:

我必须编写一个 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

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

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

【问题讨论】:

  • 您希望f='read filename' 做什么? (格式不正确;我用撇号替换了反引号。请参阅脚本的第二行。)read 函数不会将任何内容打印到标准输出;而是将输入存储在$filename 中。 $f 将是空字符串。
  • 它应该从键盘读取。我需要把它放在``之间才能工作,我需要给他一个参数
  • 不,您不需要使用反引号。只需写read filename;它会将变量$filename 设置为用户类型。使用$filename 而不是$f
  • 如果你把撇号不正确。但是我以前用过反引号,它起作用了。 @KeithThompson
  • 所以我用f=read filename 试过了。我在第 2 行得到这个:文件名:未找到。 @KeithThompson

标签: linux bash file shell directory


【解决方案1】:
  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 ]
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多