2

I want to decrypt the selected text if the string "-----BEGIN PGP MESSAGE-----" occurs in the selected text. I have the following code but it doesn't show up anything.

#!/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

When I run it on terminal after selecting a text it says

line 3: [grep: command not found

I'm new to bash scripting. Any help would be appreciated.
Thank you

1
  • There should be a whitespace between [ and grep. In addition you should test grepoutput against something.
    – drcelus
    Aug 27, 2012 at 7:06

3 Answers 3

4

Confusingly, [ is actually a program, it is also know as test (1). You do not need to enclose your grep command in a [. If you were going to use [ for something you need to seperate the left bracket with a space character [ foo == bar ]

The if syntax is: 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. 

The command you want is probalby more like this.

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

There should be a space after [. And grep returns strings so your test could fail. You better check exit status of grep.

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

[ is a command, not a syntax. It's equivalent to the test command.

Remove the square brackets to see if it works:

#!/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

UPDATE:

Insert a space after the left bracket also doesn't work in your case:

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

because bash expands it as:

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

and you'll get the line 3: [: too many arguments error.

Remember that [ is a command. It takes arguments and procedures an exit code.

You can also discard the standard output of the grep by using:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .