开发者

string comparison with slashes in shellscript

I defined a function in bash shell to search through an array of strings and determine if the input string exists. It doesn't work on strings with slashes. Please see the code below:

#!/bin/bash
in_array(){
    search_path="$1"
    shift

    while [ -n "${1+defined}" ]
    do
        echo $1 $search_path
        if [ $1 = $search_path ]
        then
            r开发者_高级运维eturn 0
        fi
        shift
    done
    return 1
}

exclude_dirs=( '/home/backup' '/home/xxx' )
in_array 'home/backup' ${exclude_dirs[@]}
echo $?

Can you explain why?


you are missing a slash. should be

in_array '/home/backup' ${exclude_dirs[@]}

you already had this: echo $1 $search_path in your code. It should show you clearly where you are wrong.


Because you are missing the initial slash in the first argument to your test case:

home/backup

vs

/home/backup
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜