basename command not working as expected basename command not working as expected shell shell

basename command not working as expected


The basename command has two uses, stripping path prefixes and (optionally) stripping suffixes.

To strip a path prefix, you can simply pass it a path, for example

basename /path/to/file.ext# file.ext

To additionally strip a suffix, you need to tell basename the suffix you wish to strip, for example

basename /path/to/file.ext .ext# filebasename DSCN2612.JPG .JPG# DSCN2612

So, basename won't "auto-detect" a suffix because in unix, files don't necessarily have suffixes. In other words, letters after a period aren't necessarily suffixes, so you need to explicitly tell it what suffix to strip.

There are some bash-specific alternatives to "auto-detect" and strip, however. For example,

x="file.ext"echo ${x%.*}# file

Without knowing more, I might write your script as

for jpg in *.JPG; do    base=${jpg%.*}    convert "$jpg" "$base.pdf"done