Using imbedded commands inside expr(1)

Bob McGowen x4312 dept208 bob at wyse.wyse.com
Fri Nov 9 03:49:58 AEST 1990


In article <1462 at eastman.UUCP> gerwitz at kodak.com (Paul Gerwitz) writes:
>I seem to be having trouble using expr.  The following dies:
>
>    test=`expr `tail +3 file` + 1` 
>
>    Basically get a numeric value from a file and increment it, putting the
>    result in a shell variable.
>

....

It seems that there may be two problems with what you are doing.  You should
check your manual for tail.  Mine states that the command that you are
using will begin at the third line of "file" and print from that point to
the end.  So if your file has more than 3 lines the result of the first
step will confuse the second (expr will get multiple items before the
plus sign and will bomb. This will also happen if the single line has
more than one item.).  The second issue is the escaping of the grave
quotes (backquotes).

Try the following:

  a)  create a file with a single number in it (such as file "num",
      content is the digit "3").

  b)  create a script file with the following lines and run it:

	    #!/bin/sh
	    val=`expr \`cat num\` + 1`
	    echo val is $val

  c)  the result will be "val is 4" for the Bourne shell, probably also
      for ksh.

You could use head +1 to get the first line in "file", tail -1 to get
the last line.  If you want a line from the middle you will need to
try some other utility, perhaps awk.

Bob McGowan  (standard disclaimer, these are my own ...)
Product Support, Wyse Technology, San Jose, CA
..!uunet!wyse!bob
bob at wyse.com



More information about the Comp.unix.shell mailing list