bash: strip file extension or path


  • filename=$(basename "$fullfile")
  • extension="${filename##*.}"
  • filename="${filename%.*}"

you could even write filename="${fullfile##*/}" and avoid calling an extra basename

This "solution" does not work if the file does not have an extension -- instead, the whole file name is output, which is quite bad considering that files without extensions are omnipresent.

Fix for dealing with file names without extension: extension=$([[ "$filename" = *.* ]] && echo ".${filename##*.}" || echo ''). Note that if an extension is present, it will be returned including the initial ., e.g., .txt


for reference, see shell-parameter-expansion