How to use the command 'shift' (with examples)
The ‘shift’ command is a shell built-in command that allows you to shift the arguments passed to the calling function or script by a specified number of places. It is particularly useful when you want to process a variable number of command-line arguments and need to handle them one by one.
Use case 1: Move arguments by one place dropping the first argument
Code:
shift
Motivation:
Sometimes, you might want to process a variable number of command-line arguments but ignore the first argument. The ‘shift’ command in this use case helps you achieve that by shifting the arguments by one place and dropping the first argument.
Explanation:
- The ‘shift’ command without any argument simply moves all the command-line arguments by one place, effectively eliminating the first argument. The subsequent arguments are then reassigned to the respective positions.
Example OUTPUT:
Suppose you have a shell script named ‘process_arguments.sh’ with the following code:
#!/bin/bash
echo "Processing arguments: $@"
shift
echo "New arguments after shifting: $@"
When you run the script with the following command:
$ ./process_arguments.sh arg1 arg2 arg3
The output will be:
Processing arguments: arg1 arg2 arg3
New arguments after shifting: arg2 arg3
Use case 2: Move arguments by N places dropping the first N arguments
Code:
shift N
Motivation:
In some scenarios, you may want to ignore the first N arguments and only process the remaining arguments. The ‘shift’ command in this use case allows you to accomplish this by shifting the arguments by N places and dropping the first N arguments.
Explanation:
- The ‘shift N’ command moves the command-line arguments by N places, effectively eliminating the first N arguments. The subsequent arguments are then reassigned to the respective positions.
Example OUTPUT:
Consider the same shell script ‘process_arguments.sh’ as in the previous example. If you modify the script by adding ‘shift 2’ before printing the new arguments, like this:
#!/bin/bash
echo "Processing arguments: $@"
shift 2
echo "New arguments after shifting: $@"
When you run the script with the following command:
$ ./process_arguments.sh arg1 arg2 arg3
The output will be:
Processing arguments: arg1 arg2 arg3
New arguments after shifting: arg3
Conclusion:
The ‘shift’ command provides a convenient way to move and drop command-line arguments in shell scripts. Whether you want to ignore the first argument or a range of arguments, the ‘shift’ command allows you to manipulate the arguments easily. By understanding and utilizing this command effectively, you can handle variable numbers of command-line arguments efficiently in your shell scripts.