Bash: Get The Last Argument Passed to a Shell Script

In a bash shell script, you can get the last argument passed to the script using the "$!" syntax. Here’s an example:

#!/bin/bash
last_argument="${!#}"
echo "The last argument passed to the script is: $last_argument"

In this example, "${!#}" expands to the value of the last argument passed to the script. The # symbol represents the number of positional parameters, and the ! symbol specifies that the value should be referenced by its index.

You can also use the "$@" syntax to refer to all of the positional parameters, and then select the last one using the "${array[-1]}" syntax:

#!/bin/bash
positional_parameters=("$@")
last_argument="${positional_parameters[-1]}"
echo "The last argument passed to the script is: $last_argument"

In this example, "$@" expands to all of the positional parameters, and the positional_parameters array is created to store these values. The "${array[-1]}" syntax then selects the last element of the array, which is the last argument passed to the script.

Leave a Comment