bash 脚本:如何测试列表成员资格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4317517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:00:38  来源:igfitidea点击:

bash scripting: How to test list membership

bashshell

提问by kjetil b halvorsen

(This is debian squeeze amd64)

(这是 debian 挤压 amd64)

I need to test if a file is a member of a list of files. So long my (test) script is:

我需要测试一个文件是否是文件列表的成员。这么长时间我的(测试)脚本是:

set -x
array=$( ls )
echo $array
FILE=log.out
# This line gives error!
if $FILE in $array
then   echo "success!"
else  echo "bad!"
fi
exit 0

?Any ideas?

?有任何想法吗?

Thanks for all the responses. To clarify: The script given is only an example, the actual problem is more complex. In the final solution, it will be done within a loop, so I need the file(name) to be tested for to be in a variable.

感谢所有的回应。澄清:给出的脚本只是一个例子,实际问题更复杂。在最终的解决方案中,它将在循环中完成,因此我需要测试文件(名称)是否在变量中。

Thanks again. No my test-script works, and reads:

再次感谢。没有我的测试脚本有效,并读取:

in_list() { local search="" shift local list=("$@") for file in "${list[@]}" ; do [[ "$file" == "$search" ]] && return 0 done return 1 } # # set -x array=( * ) # Array of files in current dir # echo $array FILE="log.out" if in_list "$FILE" "${array[@]}" then echo "success!" else echo "bad!" fi exit 0

回答by moinudin

if ls | grep -q -x t1 ; then
  echo Success
else
  echo Failure                                                                                
fi

grep -xmatches full lines only, so ls | grep -xonly returns something if the file exists.

grep -x仅匹配整行,因此ls | grep -x仅在文件存在时才返回内容。

回答by glenn Hymanman

If you just want to check if a file exists, then

如果你只是想检查一个文件是否存在,那么

[[ -f "$file" ]] && echo yes || echo no

If your array contains a list of files generated by some means other than ls, then you have to iterate over it as demonstrated by Sorpigal.

如果您的数组包含通过除 之外的其他方式生成的文件列表ls,那么您必须按照 Sorpigal 的演示对其进行迭代。

回答by sorpigal

How about

怎么样

in_list() {
    local search=""
    shift
    local list=("$@")
    for file in "${list[@]}" ; do
        [[ $file == $search ]] && return 0
    done
    return 1
}

if in_list log.out * ; then
    echo 'success!'
else
    echo 'bad!'
fi

EDIT: made it a bit less idiotic.

编辑:让它不那么愚蠢。

EDIT #2: Of course if all you're doing is looking in the current directory to see if a particular file is there, which is effectively what the above is doing, then you can just say

编辑#2:当然,如果您所做的只是查看当前目录以查看是否存在特定文件,这实际上就是上面所做的,那么您可以说

[ -e log.out ] && echo 'success!' || echo 'bad!'

If you're actually doing something more complicated involving lists of files then this might not be sufficient.

如果您实际上正在做一些涉及文件列表的更复杂的事情,那么这可能还不够。