Using linux basename to get an Azure resource name
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 outputs MyWebapp