简体   繁体   English

Shell脚本问题“ if [-[-d $ {directory}]”

[英]Shell script problems with “if [ -d ${directory} ]”

I want to do something like the following loop to find all the "*e-0[1-9]" directories in a path (1e-04,3e-07 and so on..). 我想执行以下循环操作,以在路径(1e-04、3e-07等)中找到所有“ * e-0 [1-9]”目录。 If such a directory is found, I want some commands to be executed. 如果找到这样的目录,我希望执行一些命令。 My problem is the if condition, which gives me different errors using sh or bash . 我的问题是if条件,它使用shbash给我不同的错误。 The error I get for sh is "[: unexpected sequence" and for bash is "[: too many arguments". 对于sh,我得到的错误是“ [:意外序列”,对于bash,则是“ [:过多参数”。 I found this problem in different questions in stackoverflow, but these problems where mostly related to a conversion from "==" to "=" in the if-condition, which is not the case here. 我在stackoverflow的其他问题中发现了此问题,但是这些问题主要与if条件中从“ ==”到“ =”的转换有关,在这里不是这种情况。 The problem part looks like this: 问题部分如下所示:

for i in `seq 1 9`;
do
    directory=*e-0$i
    // directory="*e-0"+$i    // also tried things like that
    if [ -d ${directory} ]    // THIS is the line stated in the error
    then
        echo $directory
    fi
done

Thanks in advance. 提前致谢。

Use More Quotes™ : 使用更多报价™

if [ -d "$directory" ]

Or a simpler approach to the whole loop: 更简单的方法来处理整个循环:

shopt -s nullglob
for directory in *e-0[1-9]/

This doesn't need to check if there's a match, because the loop body will only be run for the matching paths. 这不需要检查是否存在匹配项,因为循环主体将仅针对匹配路径运行。 The trailing slash ensures that it only matches directories 斜杠确保仅匹配目录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM