我在bash shell中定义了一个函数,用于搜索字符串数组并确定输入字符串是否存在。它对带斜杠的字符串不起作用。请参阅下面的代码:
#!/bin/bash
in_array(){
search_path="$1"
shift
while [ -n "${1+defined}" ]
do
echo $1 $search_path
if [ $1 = $search_path ]
then
return 0
fi
shift
done
return 1
}
exclude_dirs=( '/home/backup' '/home/xxx' )
in_array 'home/backup' ${exclude_dirs[@]}
echo $?
你能解释为什么吗?
你少了一个斜杠。应该是
in_array '/home/backup' ${exclude_dirs[@]}
你的代码中已经有了这个:echo $1 $search_path
。它应该能清楚地告诉你哪里错了。
因为您在测试用例的第一个参数中缺少初始斜杠:
home/backup
和
/home/backup