如何在Bash脚本中搜索">"符号

3

我正在编写一些脚本来创建一个目录,但是我希望首先确保用户输入的名称是正确的。为此,我写了类似下面这样的代码(FILE.txt是保存用户名的文件)

if grep -q  '>' FILE.txt
  then
  echo "You should avoid inserting ">" in your code!"
  fi

但是似乎bash认为我想要插入输出,所以它会给出这个错误: -sh:'newline'附近有语法错误 有人有什么想法吗?谢谢帮助


每当引用出现问题时,我总是喜欢向人们推荐这个答案:https://dev59.com/qGw05IYBdhLWcg3wahJM#9712555 :-) - ghoti
2个回答

5
问题不在于你的 grep 命令行,而在于你的 echo 命令行。你的 shell 将其视为:
echo "You should avoid inserting "  >  " in your code!"

您可以通过去掉句子中间的引号或使用单引号来简单解决此问题,例如:

echo "You should avoid inserting '>' in your code!"

我认为 OP 想要像这样保存 > 周围的 ""echo You should avoid inserting '">"' in your code! - Arkadiusz Drabczyk

1

您需要在echo语句中转义引号:

if grep -q '>' file.txt; then
    echo "You should avoid inserting \">\" in your code!"
else
    echo "code is good"
fi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接