Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question
    
There should be a whitespace between [ and grep. In addition you should test grepoutput against something. –  drcelus Aug 27 '12 at 7:06
add comment

3 Answers 3

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
share|improve this answer
add comment

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
share|improve this answer
add comment

[ 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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.