[Top][All Lists]

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

exiting noninteractive shells on 'shift 2'

From: Eric Blake
Subject: exiting noninteractive shells on 'shift 2'
Date: Thu, 8 Nov 2018 14:37:11 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.3.0

If I'm reading POSIX correctly, shift is a special built-in utility, and if '$#' is 0 or 1, then 'shift 2' counts as a utility error that shall exit the shell, per the table in 2.8.1 Consequences of Shell Errors:


dash gets this right:

$ dash -c 'set 1
> shift 2
> echo "oops"'
dash: 2: shift: can't shift that many

but bash happily lets 'shift 2' fail with $? set to 1 but continues on with execution of the rest of the script, even when in POSIX mode:

$ bash -c 'set 1
> shift 2
> echo "oops"'
$ bash -c 'set 1; set -o posix
> shift 2
> echo "oops"'

I spent more than an hour today figuring out why my shell script was inf-looping, and traced it back to failure to check for non-zero status from 'shift 2', where I had been expecting immediate hard failure of the entire script. I don't care if bash doesn't hard-exit when not in POSIX mode, and it must not hard-exit when in interactive use; but the non-interactive use not doing a hard exit seems like a bug.

On the other hand, the POSIX wording for shift, under EXIT STATUS, weakens the "shall fail" from the earlier table into a weaker "may fail":


If the n operand is invalid or is greater than "$#", this may be considered a syntax error and a non-interactive shell may exit; if the shell does not exit in this case, a non-zero exit status shall be returned. Otherwise, zero shall be returned.

Tested on Fedora 28 with bash-4.4.23-1.fc28.x86_64

Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org

reply via email to

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