Curious ksh hack

John Rupley rupley at arizona.edu
Sat Mar 12 13:39:34 AEST 1988




In article <340 at manta.UUCP>, brant at 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 _<shellargs>=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 at linc.cis.upenn.edu, UUCP: ...drexel!manta!brant

John Rupley
 uucp: ..{ihnp4 | hao!noao}!arizona!rupley!local
 internet: rupley!local at 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"



More information about the Comp.sys.att mailing list