Linux Know-How provides a collection of introductory texts on often needed Linux skills. |
Home Bash Guide for Beginners Repetitive tasks The shift built-in | |||||||
See also: Making menus with the select built-in | |||||||
Search the VIAS Library | Index | |||||||
The shift built-inThe shift command is one of the Bourne shell built-ins that comes with Bash. This command takes one argument, a number. The positional parameters 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. Say you have a command that takes 10 arguments, and N is 4, then $4 becomes $1, $5 becomes $2 and so on. $10 becomes $7 and the original $1, $2 and $3 are thrown away. If N is zero or greater than $# (the total number of arguments, see Section 7.2.1.2). If N is not present, it is assumed to be 1. The return status is zero unless N is greater than $# or less than zero; otherwise it is non-zero. ExamplesA shift statement is typically used when the number of arguments to a command is not known in advance, for instance when users can give as many arguments as they like. In such cases, the arguments are usually processed in a while loop with a test condition of (( $# )). This condition is true as long as the number of arguments is greater than zero. The $1 variable and the shift statement process each argument. The number of arguments is reduced each time shift is executed and eventually becomes zero, upon which the while loop exits. The example below, cleanup.sh, uses shift statements to process each file in the list generated by find:
In the next example, we modified the script from Section 8.2.4.4 so that it accepts multiple packages to install at once:
|
|||||||
Home Bash Guide for Beginners Repetitive tasks The shift built-in |