Bash: Get Filename or Extension from Path

2018-01-02 ·
#!/bin/bash

fullpath="/etc/nginx/nginx.conf"
filename=$(basename "$fullpath")
echo $filename
nginx.conf

Drop the extension

#!/bin/bash

fullpath="/etc/nginx/nginx.conf"
filename=$(basename "$fullpath")
fname="${filename%.*}"
echo $fname
nginx

Just the extension

#!/bin/bash

fullpath="/etc/nginx/nginx.conf"
filename=$(basename "$fullpath")
ext="${filename##.*}"
echo $ext
conf

For more details, check shell parameters expansion in Bash manual.

In general,

  • ${variable%pattern} - Trim the shortest match from the end
  • ${variable##pattern} - Trim the longest match from the beginning
  • ${variable%%pattern} - Trim the longest match from the end
  • ${variable#pattern} - Trim the shortest match from the beginning
Copyright © 2018 All rights reserved.
Powered by Kulfon.