【问题标题】:I am having a hard time why the if statements don't work in ShellScript我很难理解为什么 if 语句在 ShellScript 中不起作用
【发布时间】:2018-08-01 20:31:09
【问题描述】:

我很难理解为什么当我输入最随机的名称时,它们会被接受为目录。当一个 if 语句检查它是否是一个可读文件时,它对我输入的所有内容都说是。这里的目标是搜索一个目录,检查它是否是一个目录。然后在目录中搜索一个文件,然后在该文件中使用 forloops 搜索其中的单词。 while 循环是询问文件名 3 次。有点粗略,我只需要解释一下 if 语句不起作用

 #!/bin/sh

DIR='/home/collin2/'
x=1
echo "Please enter directory"
read directory

for directory in "$DIR"; 
do
        if [ -d  "$directory" ]; 
    then echo "This is a directory Please enter the file name"
            read filename
            while [ $x -le 3 ]; do

            for filename in  "$directory";
        do
            if [ -r "$filename" ]
            then echo "The filename is readable" 
                echo "Please Enter a word "
                read word
                grep "$word" "$filename"
                exit 1


            fi

        done
        echo "Doesn't exist please try again"
        read filename 


        x=`expr $x + 1`

            done


     #exit 1

        fi

done
 echo "not a directory"

退出 0

【问题讨论】:

  • 当您遇到 shell 脚本问题时,最好的第一步是将您的代码剪切并粘贴到 shellcheck.net 并更正它识别的错误(重要)和警告(可能很重要)。如果您无法理解它的消息,或者您已经解决了所有问题但问题仍然存在,那么请来这里问一个人。

标签: shell for-loop search directory


【解决方案1】:

您的for 命令有误:

当你写for directory in "$DIR";时,它会将变量directory的值设置为"$DIR"。您想检查一下,您是否可以在 "$DIR" 中找到 directory,这可以在没有 for 命令的情况下完成:

cd "$DIR" || { echo "Can not go to $DIR"; exit 1; }
test -d "${directory}" || { echo "Wrong directory ${directory}"; exit 1; }
# or
test -d "$DIR/${directory}" || { echo "Can not go to $DIR"; exit 1; }

另一个for循环也有同样的问题。

测试if [ -r "$filename" ] 应该在cd "$DIR/${directory}" 之后进行或包含完整路径。

【讨论】:

  • 为什么 if 语句不起作用但是您的方法解决了问题是没有意义的。谢谢
猜你喜欢
  • 2012-07-21
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多