在BASH中的选定文本中searchstring/模式

如果在选定的文本中出现string“—– BEGIN PGP MESSAGE —–”,我想解密选定的文本。 我有下面的代码,但它不显示任何东西。

#!/bin/bash xsel > pgp.txt if [grep -e "-----BEGIN PGP MESSAGE-----" pgp.txt] then gnome-terminal --command "gpg -d -o decrypted.txt pgp.txt" gedit decrypted.txt fi 

当我select一个文本后,在terminal上运行它说

 line 3: [grep: command not found 

我是新来的bash脚本。 任何帮助,将不胜感激。
谢谢

令人困惑的是, [其实是一个程序,它也被称为testing(1) 。 你不需要把你的grep命令放在一个[ 。 如果你打算使用[你需要用空格字符[ foo == bar ]来分隔左括号[ foo == bar ]

if语法是: help if

 if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi The `if COMMANDS' list is executed. If its exit status is zero, then the `then COMMANDS' list is executed. 

你想要的命令更像这样。

 if grep -q -e "-----BEGIN PGP MESSAGE-----" pgp.txt; then ... ... fi 

[后面应该有一个空格。 而grep返回string,所以你的testing可能会失败。 你最好检查grep的退出状态。

 grep -e "-----BEGIN PGP MESSAGE-----" pgp.txt exitcode=$? if [ $exitcode ] then # not found else # found fi 

[是一个命令,而不是一个语法。 这相当于test命令。

删除方括号,看看它是否工作:

 #!/bin/bash xsel > pgp.txt if grep -e "-----BEGIN PGP MESSAGE-----" pgp.txt then gnome-terminal --command "gpg -d -o decrypted.txt pgp.txt" gedit decrypted.txt fi 

更新:

在左括号之后插入一个空格在您的情况下也不起作用:

 if [ grep -e "-----BEGIN PGP MESSAGE-----" pgp.txt ] then 

因为bash扩展它为:

 if test grep -e "-----BEGIN PGP MESSAGE-----" pgp.txt then 

你会得到第line 3: [: too many arguments错误。

请记住, [是一个命令。 它需要参数和程序退出代码。

你也可以使用下面的命令来放弃grep的标准输出:

 if grep -e "-----BEGIN PGP MESSAGE-----" pgp.txt >/dev/null then