Home

Using linux basename to get an Azure resource name

til azure shell

When working with Azure, you’ll often need to extract the name of a resource from its full ID. The basename utility in Linux can help with this.

I had previously only used basename to derive a file name from a file path, so was pleased to come across this use case.

Azure Resource ID example

I found it very difficult to find a good example of an Azure resource ID in the Microsoft documentation. However, Azure CLI to the rescue.

If we run az resource show --help then we see an example resource ID for a Web Application:

/subscriptions/0b1f6471-1bf0-4dda-aec3-111111111111/resourceGroups/MyResourceGroup/providers/Microsoft.Web/sites/MyWebapp

Use the linux basename utility

From man basename we read:

The basename utility deletes any prefix ending with the last slash ‘/’ character present in string (after first stripping trailing slashes), and a suffix, if given.

Bash shell example

#!/usr/bin/env bash
set -euo pipefail

resourceId=/subscriptions/0b1f6471-1bf0-4dda-aec3-111111111111/resourceGroups/MyResourceGroup/providers/Microsoft.Web/sites/MyWebapp
result=$(basename "${resourceId}")
echo "${result}"

This outputs MyWebapp

Trailing slashes are handled too

#!/usr/bin/env bash
set -euo pipefail

resourceId=/subscriptions/0b1f6471-1bf0-4dda-aec3-111111111111/resourceGroups/MyResourceGroup/providers/Microsoft.Web/sites/MyWebapp/
result=$(basename "${resourceId}")
echo "${result}"

This also outputs MyWebapp

Classical usage - extract filename from a file path

The classical way I’ve seen basename used is

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_NAME=$(basename "$0")
echo "This script's name is: ${SCRIPT_NAME}"

SCRIPT_NAME_NO_SUFFIX=$(basename "$0" .sh)
echo "This script's name without the .sh suffix is: ${SCRIPT_NAME_NO_SUFFIX}"

If for example that script were called base.sh, we can expect the following output:

This script's name is: base.sh
This script's name without the .sh suffix is: base

The man page continues:

A non-existent suffix is ignored.

So if we renamed the script base, and re-ran, we can expect the following output:

This script's name is: base
This script's name without the .sh suffix is: base