shell中if 变量里包含字符串的判断(转)
参考:
http://bbs.chinaunix.net/thread-1633281-1-1.html
需求:
判断变量cache_dir中是够包括"/data/cache"字符串
法1:
1
2
3
if [[ "${cache_dir}" =~ "/data/cache" ]]; then
echo "true"
fi
法2:
1
2
3
if [[ ${cache_dir} = */data/cache* ]]; then
echo "true"
fi
法3:
1
2
3
if echo ${cache_dir} |grep -q "/data/cache"; then
echo "true"
fi
法4:
1
echo ${cache_dir} |grep -q "/data/cache" && echo "true" || echo "false"
特别说明,以上方法适用于所有遵从POSIX的shell,如ksh。