Re: bash vs ksh problem
From: Dan Mercer (dmercer_at_mn.rr.com)
Date: 06/01/04
- Previous message: Dan Mercer: "Re: list of files modified after a given date"
- In reply to: Aquarius2431: "bash vs ksh problem"
- Next in thread: gregg: "Re: bash vs ksh problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 01 Jun 2004 15:50:49 GMT
"Aquarius2431" <aquarius2431@yahoo.com> wrote in message news:c2d830c4.0406010355.2a6fd130@posting.google.com...
: Using the ksh this simple test program
: works as expected:
:
: #!/bin/ksh
:
: x=1
: while [ x -lt 10 ]
You should have specified $x. However, in ksh, the context with
which a token is used can coerce it to that context. In this case
the token "x" is used in a numeric context, so instead of treating
it as a literal "x" it treats it as the variable x. This coercion
is recursive, up to a limit:
$ z=1
$ y=z
$ x=y
$ [ x -lt 2 -a x -gt 0 ] && echo ok
ok
This is very useful at times but also can create some pretty hairy
problems to debug, as you've seen.
BTW, you ought to write ksh syntax if you go to all the trouble
to use "#!/bin/ksh" in your shebang:
typeset -i x=1
while (( x < 10 ))
do
...
(( x = x + 1))
done
also, because of the coercion feature and our typesetting
the variable as an integer, you can simply do:
x=x+1
ksh sees that as three tokens: "x", "=" and "x+1". Using the coercion
feature, it knows, that "x" can't be set to a string value, so it
recursively treats the string as an arithmetic expression. This will
not work correctly without the typeset. Instead, x will be set
to the string "x+1". When it gets to the test (( x < 10 )), it will
substitute "x+1" for x, then again substitute "x+1" for that x until
the recursion limit is reached (I think recursion is set to 200 levels).
It can be a powerful feature, but is also a very dangerous one.
Dan Mercer
: do
: echo $x
: x=`expr $x + 1`
: done
:
:
: And here is the output:
:
: $ ./loop2
: 1
: 2
: 3
: 4
: 5
: 6
: 7
: 8
: 9
:
: However on RH Linux using bash (/bin/sh on Linux)
: it produces this error:
:
: $ ./loop
: ./loop: line 4: [: x: integer expression expected
:
:
: It appears to be failing evaulating this line:
:
: while [ x -lt 10 ]
:
: Is this some sort of known problem perhaps?
: This is on Redhat Linux 8.0.
:
:
: lk
: www.theNewAgeSite.com
- Previous message: Dan Mercer: "Re: list of files modified after a given date"
- In reply to: Aquarius2431: "bash vs ksh problem"
- Next in thread: gregg: "Re: bash vs ksh problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|