shell programming question: help with expr command

Polytropon freebsd at edvax.de
Sat Apr 9 15:57:32 UTC 2011


On Sat, 9 Apr 2011 06:31:28 -0700 (PDT), Dino Vliet <dino_vliet at yahoo.com> wrote:
> Hi folks,
> I'm having trouble with a little shell script. Can somebody
> explain me why I get 3 times "expr: syntax  error" in my
> console after I run this little script?
> 
> #! /usr/local/bin/bash
> # testscript 
> 
> var1="trees.J48" #other value will be rules.Jrip, rules.DecisionTable
> len=${#var1}
> ind=`expr index $var1 s`
> pos=`expr $len - $ind`
> out=`expr substr $var1 $ind $pos` 
> 
> I would expect (and want the following to happen):
> 
> $ind should contain 6
> $pos should contain 3
> $out should contain J48 (other values will have to be Jrip,DecisionTable)
> 
> Can anyone help me with this?

The explaination is quite simple: expr doesn't know "index"
or "substr"; see "man expr" for details.

A polite sidenote: Unless you have a good reason to code
in bash-specific manner, do NOT #!/usr/local/bin/bash, as
this is NOT portable (if this is one of your goals); use
the standard #!/bin/sh instead.

Depending on what you have in mind, maybe mentioning the
strengths of perl, sed and awk is worth being mentioned. :-)



-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...


More information about the freebsd-questions mailing list