循环时避免扩展:对于$ foo中的x

Kok*_*kol 2 bash shell for-loop wildcard expansion

我必须计算目录中的可执行文件数.

我已经想出了一种不同的方法(通过写入文件然后搜索文件,但这有点难看).

首先来到我的解决方案是这个(第一个参数是目录路径):

#!/bin/bash

noe=0

files=`ls -F $1` # because the -F option appends an indicator
                 # to the file, for an executable it's an '*'
                 # so if there is an executable 'script.sh' in the dir
                 # the output will be like this: 'script.sh*'

for i in $files
do
    if [ `echo "$i" | grep '*$'` ] #should search for an '*' at the end...
    then
        let noe += 1
    fi
done

echo $noe
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为for循环中省略了'*'.

(for循环中的echo命令最后输出一个没有'*'的文件名,但是当参数在""中时,在for循环外正常工作)

有关于这一个类似的问题在这里,我已经成功地回答适应我的情况,但它没有解释为什么它不能与完成.+我不完全理解为什么<在while循环中还有一个额外的东西

...
done < <(ls -F $1) 
     ^
     |_ I know that this means redirect to file to loop
        Does the second < mean that we are redirecting the
        standard input file? (this might be a stupid question)
Run Code Online (Sandbox Code Playgroud)

另一个问题:for循环是否有解决方法?为什么?

gei*_*rha 6

这个问题的解决不应在任何情况下参与ls.

您可以使用for循环迭代文件并使用-x测试来确定文件是否可执行.但是,目录通常也是可执行的(如果它们不是,你不能输入它们,例如cd),所以根据你是否要在结果中包含目录,你可能也需要-d测试.例:

for file in ./*; do
    if [[ -x $file && ! -d $file ]]; then
        printf '<%s> is an executable file that is not a directory\n' "$file"
        (( count++ ))
    fi
done
printf '%d executable files found\n' "$count"
Run Code Online (Sandbox Code Playgroud)

至于第二个问题:

...
done < <(ls -F $1) 
     ^
     |_ I know that this means redirect to file to loop
        Does the second < mean that we are redirecting the
        standard input file? (this might be a stupid question)
Run Code Online (Sandbox Code Playgroud)

<(...)是进程替换,并由文件名替换为fd或命名管道(取决于操作系统支持的内容).从此fd或命名管道读取的任何进程都将获得该命令的输出(stdout)<(...)

你可以通过echo使用它来看到这个:

$ echo <(true)  # turns into  echo /dev/fd/63
/dev/fd/63
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下,done < <(ls...)变成类似的东西done < /dev/fd/63,这是你已经熟悉的标准文件重定向.

  • 请参阅http://mywiki.wooledge.org/ParsingLs,了解为什么使用这样的`ls`是一个坏主意. (3认同)