Bash: Get The Last Argument Passed to a Shell Script

Bash: Get The Last Argument Passed to a Shell Script

To get the last argument passed to a Bash shell script, you can use the "$0" special parameter.

The "$0" parameter represents the name of the script itself, and it is the first element in the "$@" array, which contains all of the arguments passed to the script.

To get the last argument passed to the script, you can use the "${!#}" parameter expansion, which expands to the last element in the "$@" array.

For example, consider the following script myscript.sh:

#!/bin/bash

echo "The last argument passed to the script is: ${!#}"
Sou‮www:ecr‬.lautturi.com

To run the script and get the last argument passed to it, you can use the following command:

./myscript.sh arg1 arg2 arg3

This will output the following:

The last argument passed to the script is: arg3

You can also use the "${@: -1}" parameter expansion to get the last argument passed to the script. This expansion expands to the last element in the "$@" array, and is equivalent to "${!#}".

For example, you can use the following command to get the last argument passed to the script:

echo "The last argument passed to the script is: ${@: -1}"

Keep in mind that the "${!#}" and "${@: -1}" expansions only work if the script has at least one argument passed to it. If the script is called without any arguments, these expansions will expand to an empty string.

You can use the "$#" parameter to check the number of arguments passed to the script, and handle the case where no arguments are passed appropriately.

Created Time:2017-10-27 14:56:35  Author:lautturi