我正在编写一个非常简单的脚本,它将文件复制到用户提供的路径作为参数,我想确保路径以 / var / log / messages 开头。< / p>
所以我写了这个:
if [[ $2 -ne /var/log/messages/* ]]
then
echo "Incorrect path, must be under /var/log/messages/"
exit
fi
但它似乎不起作用。
我做错了什么?
答案 0 :(得分:3)
这应该有效:
if [[ "$2" != "/var/log/messages/"* ]]
then
echo "Incorrect path, must be under /var/log/messages/"
exit
fi
答案 1 :(得分:1)
您通常应提供最小的非工作示例。但是,我怀疑你想要:
if [[ $2 != /var/log/messages/* ]]
then
echo "Incorrect path, must be under /var/log/messages/"
exit
fi
答案 2 :(得分:1)
您可以使用regular expressions as well(从Bash版本3开始)。请记住这一点:
正则表达式的每个引用部分都是字面意思,即使它包含正则表达式特殊字符。
在这种情况下,你可以这样做:
if [[ ! "$2" =~ ^"/var/log/messages/" ]]
then
echo "Incorrect path, must be under /var/log/messages/"
exit
fi
答案 3 :(得分:0)
您可以使用dirname
:
if [[ `dirname $2` != "/var/log/messages" ]]
then
echo "Incorrect path, must be under /var/log/messages/"
exit
fi
答案 4 :(得分:0)
UNTESTED:
...
case $2 in
/var/log/messages/*) ;;
# do whatever...
*)
echo "incorrect ..."
break
;;
esac
...