【问题标题】:Cannot enter if loop at bash script无法在 bash 脚本中输入 if 循环
【发布时间】:2016-08-16 01:19:10
【问题描述】:

我想创建一个 bash 脚本,它将命令行中的一个目录作为参数并打印我的所有子目录。我的脚本打印了这个目录所有的文件,并且没有进入 if 循环。我做错了什么以及如何解决?

#!/bin/bash
echo to argv[1] = $1
if [ -e $1 ] #exist the file
then if [ -d $1 ] # is directory
    then if [ -r $1 ] #we can read
        then for k in $(ls $1) #all the files in the arv[1] 
        do
            echo $k #print all the files of directory
            if [ -d $k ]
                then echo $k
            fi
        done
    fi
  fi
fi

【问题讨论】:

    标签: bash shell loops scripting directory


    【解决方案1】:

    [ -d $k ]测试$k是否为相对于当前工作目录的目录,但需要使用

    [ -d "$1/$k" ]
    

    改为。

    另外,不要迭代 ls 的输出,而是使用

    for k in $1/*
    

    这使得上述更改变得不必要。

    顺便说一句,whileuntilfor 开始循环,但 if 没有。我称之为“if 块”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 2014-08-25
      • 1970-01-01
      相关资源
      最近更新 更多