shell: "can't shift that many" error

7

1

The following script works fine in one of my machines, printing 1 then 2:

#!/bin/sh

echo "1"
shift
echo "2"

On another machine, however, it produces the following output:

1
./script.sh: 4: shift: can't shift that many

man shift does not help (No manual entry for shift).

What is that error, why is it happening, and how can I fix it?

anol

Posted 2015-04-02T15:56:33.443

Reputation: 1 291

Answers

9

What is shift: it is a shell built-in that works as follows (adapted from TLDP):

The shift command takes one argument, a number (if not present, it is assumed to be 1). The positional parameters (e.g. command arguments) are shifted to the left by this number, N. The positional parameters from N+1 to $# are renamed to variable names from $1 to $# - N+1.

Often you make a loop in which you process one or more arguments, then you call shift to "forget" them and loop again to process the following ones.

Error cause: The error comes from the fact that some shells (but not all) detect when there are not enough arguments for shift. In particular, dash considers it a fatal error.

Possible solutions:

  • Test if there are enough remaining arguments: if [ "$#" -gt 0 ]; then shift; fi

  • Add a conditional argument: shift $(( $# > 0 ? 1 : 0 ))

anol

Posted 2015-04-02T15:56:33.443

Reputation: 1 291

Just stumbled across this when I had the same problem. Thanks for posting this Q&A! You can also accept your own answer (that's considered perfectly acceptable, ba-dum-tss). (There's a two-day delay before you can accept your own answer, but I think it's safe to say that's elapsed by now.) ;) – n.st – 2018-12-08T14:27:23.477