Path: utzoo!mnetor!uunet!husc6!hao!noao!arizona!rupley From: rupley@arizona.edu (John Rupley) Newsgroups: comp.sys.att Subject: Re: Curious ksh hack Message-ID: <4310@megaron.arizona.edu> Date: 12 Mar 88 03:39:34 GMT References: <340@manta.UUCP> Organization: U of Arizona CS Dept, Tucson Lines: 64 Summary: neat hack explained In article <340@manta.UUCP>, brant@manta.UUCP (Brant Cheikes) writes: > >In a memo by David Korn describing ksh, there is a paragraph that > >states: > >If you export the startup file name in the variable START, then setting > > ENV='${START[(_$-=1)+(_=0)-(_$-!=_{-%%*i*})]}' > >will only invoke the startup file for interactive shells since the > >subscript evaluates to 0 only if the shell is interactive." > > Now, I've done this and it works, but I can't quite figure out how. > I've figured out the following: > 1. $- evaluates to the shell args, for an interactive shell this > is something like 'is', otherwise just 's'. > 2. _$-=1 evaluates to _=1, e.g., _is=1 > 3. _=0 is just _=0 > 4. _$-!=_{-%%*i*} becomes _is!=_ (if shell args contains 'i') and > _s!=_s otherwise. > So for an interactive shell, we get > (_is=1)+(_=0)-(_is!=_) > At this point I'm lost. Don't the parenthesized items invoke > subshells? How does this turn out to be 0? And how does it turn out > to be 1 if the shell is non-interactive? Awesomely neat trick! For Korn shell arithmetic, the parentheses establish high precedence. The assignments within them are just that, giving the value "1" to "_is" and "0" to "_". The value of the parenthesized expression is the assigned value. The two-fold cleverness is using the results of the first two assignments in the logical arithmetic test of the rightmost term, and then merging in the logical result (false=1 if "i" is set (1 != 0), true=0 if not) when evaluating the full expression. So the arithmetric expression evaluates: 1 + 0 - 1 if "i" is a shell parameter 1 + 0 - 0 if "i" is not a parameter Attached is a shell script that shows what happens, if you run ksh -x script for non-interactive shell ksh -i -x script for interactive shell > Brant Cheikes > University of Pennsylvania > Department of Computer and Information Science > ARPA: brant@linc.cis.upenn.edu, UUCP: ...drexel!manta!brant John Rupley uucp: ..{ihnp4 | hao!noao}!arizona!rupley!local internet: rupley!local@megaron.arizona.edu telex: 9103508679(JARJAR) (H) 30 Calle Belleza, Tucson AZ 85716 - (602) 325-4533 (O) Dept. Biochemistry, Univ. Arizona, Tucson AZ 85721 - (602) 621-3929 ---------------------------------------------------------------------- #script #run under ksh # ksh -x script # ksh -i -x script (( a1=(_$-=1) )) (( a2=(_=0) )) (( a3=(_$-!=_${-%%*i*}) )) (( a=(_$-=1)+(_=0)-(_$-!=_${-%%*i*}) )) b="${START[(_$-=1)+(_=0)-(_$-!=_${-%%*i*})]}" echo echo "INDEX= $a1 + $a2 - $a3 = $a and ENV=START[INDEX]=$b"