(这是debian squeeze amd64)
我需要测试一个文件是否是文件列表的成员。 这么久我的(测试)脚本是:
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
¿有什么想法吗?
感谢所有回复。澄清一下:给出的脚本只是一个例子,实际问题更复杂。在最终的解决方案中,它将在一个循环中完成,因此我需要将要测试的文件(名称)放在一个变量中。
再次感谢。没有我的测试脚本有效,并且显示:
in_list() {
local search="$1"
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
最佳答案
if ls | grep -q -x t1 ; then
echo Success
else
echo Failure
fi
grep -x
只匹配整行,所以 ls | grep -x
仅在文件存在时返回一些内容。
关于bash 脚本 : How to test list membership,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317517/