letter to the IT Toolbox

Table of Contents

1 Which shell am I in

The question now is "How do I know which shell I'm in?" (besides forcing #!… (sh-bang) on the first line which is guaranteed to work only if you already know the program is available on your machine).

2 Dave Korn's suggestion:

here's a portable function, at least between bash and ksh:

$ isKsh && typeset -f isKsh
isKsh() { one=1; [ one -eq 1 ] 2>/dev/null; }
$

now the same function in bash:

$ isKsh || declare -f isKsh
isKsh ()
{
    one=1;
    [ one -eq 1 ] 2> /dev/null
}
$

What does this mean? You have two choices.

  • if you are thinking ksh, then guarantee you are running in ksh, or
  • if you are thinking bash, then provide function definitions in your ksh environment to override, or emulate the bash version

2.1 here are suggested means

This is the one Dave Korn showed me ~ 30 yrs ago:

# re-starts the script in Ksh
one=1; [ one -eq 1] 2>/dev/null || exec ksh $@

# see the discussion below:

My work for the future of the functions I'll write:

# re-use where-ever needed
isKsh () { one=1; [ one -eq 1 ] 2>/dev/null; }
isKsh && {

   # define any function which may have ksh dependencies
   ...

}
#  and later ... (see discussion)
...
some_function () {

   isKsh && { # do the ksh thing

   ..; } || { # do the bash thing
   }
}

2.2 How does it work?

It turns out the assignment `one=1` and strange looking test

[ one -eq 1 ]

is TRUE in ksh but not in sh, nor as it thankfully turns out in bash. Dave felt that when used to to arithmetic the "$"varname_ was unnecessarily noisy, if not superfluous.

(side note for my UK friends: while teaching Tcl for my UK-based financial services company, I drew no small amount of delight in pointing out that the "$" (dollar) sign is the scripting language's universal token for 'the value of' )

Note, with #2, now any function you need to work in both ksh and bash, i.e a "bash" feature you can't get away with in ksh you simply embed the 'isKsh' test in the function. and a threshold of pain, i'd guess if more the 5 - 7 % of your functions require this feature, you'll need to do some factoring. The project starts with a canonical syntax for these commands or built-ins:

  • type – returns whether the command an alias, function, built-in or (executable) file
  • functions – lists the currently defined functions (ksh only, so bash needs this as an equivalent function)
  • command – a built-in which guarantees to execute any built-in or file which may be overridden by an alias or function

3 References

This note is part of my Commonplace book

Author: Marty

Created: 2016-02-20 Sat 15:48

Emacs 24.4.1 (Org mode 8.2.10)

Validate