[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: $[...] or $((...))

From: Koichi Murase
Subject: Re: $[...] or $((...))
Date: Thu, 10 Sep 2020 09:46:54 +0900

2020-09-10 9:10 Chris Elvidge <>:
> I've used 'return $((!$#))' and 'return $[!$#]' to return an error
> if no parameters given to function.

You can use

  (($#)) || return

With the above command, (($#)) fails with no parameters so that the
next command `return' is executed.  When `return' is called without
arguments, it uses $?, the exit status of the previous command, for
the function's exit status.  If you want to use the function in trap
handlers you need to explicitly specify the exit status as

  (($#)) || return "$?"

because, in trap handlers, `return' without arguments returns the exit
status of the previous command *outside the trap handler* in Bash

> However 'N=0; echo $((!$N))' gives an error at the bash prompt. 'echo
> $[!$N]' echo's 1 as expected.

This is because the construct `!...' is subject to history expansions
in interactive sessions.  You command `echo $((!$N))' will be first
expanded to `echo $((<LAST_ARGUMENT_IN_HISTORY>N))', and then the
arithmetic evaluation will be performed.  If you don't use history
expansions, you can turn it off by putting `set +H'.

The reason why `$[!$N]' didn't cause history expansions was just
because the history expansion skips the string of the form `[!...]'
which resembles the glob pattern.  It is an accidental pattern
coincidence, and $[...] cannot be always used to suppress history
expansions.  For example, `echo $[a=!$N]' is a target of the history
expansion and will cause errors.

> My question - is $[...] actually obsolete? If so, what should I use at
> the bash prompt to get the same effect?

Yes, it is obsolete.  It is a Bash-1 feature and not documented in the
current Bash manuals (Bash-2.0+).


reply via email to

[Prev in Thread] Current Thread [Next in Thread]