2025-04-23 19:38:59 EDT

M: On Linux, in a bash script, I have a variable called pile that has the name of a file with the full directory structure. I want just the file name, with the directory stripped away.

G: Use basename to strip the directory part and leave just the filename:

filename=$(basename "$pile")

This works regardless of how deep the directory structure is or whether the path has spaces.

2025-04-23 19:39:24 EDT

M: How would I get just the file name without extension?

G: To get just the file name without the extension:

name_no_ext="${pile##*/}"
name_no_ext="${name_no_ext%.*}"

Breakdown:

This works for simple extensions. If you're dealing with multiple dots (e.g., file.tar.gz) and want to strip only the last extension, this is fine. If you want to strip all extensions, you can do:

name_no_ext="${name_no_ext%%.*}"