views:

426

answers:

4

I wrote a shell script to convert HTML source to plain text using lynx.

Here it is:

#!/bin/sh

if [ -f = "/usr/bin/lynx" ]
  then
    if [ -f = "$1" ]
      then
        lynx -dump $1 > $2
      else
        echo "File $1 does not exist!"
    fi
  else
    echo "Lynx is not installed!"
fi

Now, although lynx exists in the right directory, and I pass correct arguments I get either "Lyns is not installed!" message or (if I comment the first test) "File $1 does not exist!". I'm not to good at sh so could someone tell me what is wrong with the script?

+4  A: 

I think the first if is wrong and should be replaced with

if [ -f /usr/bin/lynx ]
Flavius Stef
The same goes for the second, I think.
Rodrigo Queiro
Yes, of course :)
Flavius Stef
+2  A: 

Try removing the "-f =" and keeping it just "-f"

Jesse Dearing
A: 

It's like that now:

#!/bin/sh

if [ -f /usr/bin/lynx ]
  then
    if [ -f $1 ]
      then
        lynx -dump $1 > $2
      else
        echo "File $1 does not exist!"
    fi
  else
    echo "Lynx is not installed!"
fi

And the problem with tests is gone, but now I get this error:

line 7: $2: ambiguous redirect

although

lynx -dump site.html > site.txt works fine if run from console

You've not checked that you have supplied two file names - so $2 is empty and '>' doesn't say where to redirect the output, so it is an ambiguous redirect. Incidentally, on my machine, lynx is installed in /usr/gnu/bin or /usr/local/bin (and both are on my PATH).
Jonathan Leffler
You could reduce that to: exec ${LYNX:-lynx} -dump ${1:?} >${2:?}; that would do the same job pretty much as effectively (though the default error messages are a little crude).
Jonathan Leffler
A: 
LINKS=`which links`
if [ -x $LINKS ]; then
   ...
else
   ...
endif

What if it's not installed in /usr/bin/? What if for some reason it's not executable?

elcuco
'links' is 'lynx'! :D
Jonathan Leffler
well, links is always better then lynx... I like it better ;-)
elcuco
does is support -dump? I don't think so
Reef
actually the man says it does... and man... IMHO it looks better then lynx....but....My answer was more about the BASH code (test for the location of the command, etc) then the actual command.
elcuco