shell中if 变量里包含字符串的判断

时间:2016-08-03 06:46:13   收藏:0   阅读:919

参考:

http://bbs.chinaunix.net/thread-1633281-1-1.html


需求:

判断变量cache_dir中是够包括"/data/cache"字符串


法1:

if [[ "${cache_dir}" =~ "/data/cache" ]]; then
   echo "true"
fi

法2:

if [[ ${cache_dir} = */data/cache* ]]; then
   echo "true"
fi

法3:

if echo ${cache_dir} |grep -q "/data/cache"; then
   echo "true"
fi

法4:

echo ${cache_dir} |grep -q "/data/cache" && echo "true" || echo "false"


特别说明,以上方法适用于所有遵从POSIX的shell,如ksh。


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!