shell: "can't shift that many" error

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?


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 ))