Registered User
Registered User

Reputation: 5371

basename command not working as expected

I wrote a shell script to convert a lot of JPGs at my end to pdf

 #!/bin/bash
set -xv
for i in `ls -v *.JPG`;
 do i=$(basename "$i")
 convert "$i" "$i.pdf" ;
 done

the JPGs are

DSCN2612.JPG DSCN2618.JPG DSCN2624.JPG

and the converted pdfs I get are having names

DSCN2612.JPG.pdf DSCN2618.JPG.pdf DSCN2624.JPG.pdf

Now note the use of basename command in my shell script I expect the resulting name of pdf to be

DSCN2612.pdf DSCN2618.pdf DSCN2624.pdf

Where is the output is different. I am using Ubuntu 12.04 and basename --version shows

basename (GNU coreutils) 8.13 Copyright (C) 2011 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.

when on a terminal I just type

basename DSCN2612.JPG
I get the output

DSCN2612.JPG

where as I expect

DSCN2612

only so is my understanding wrong or there is some error the way I am using this script.

Upvotes: 5

Views: 10752

Answers (1)

jedwards
jedwards

Reputation: 30240

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
# file

basename 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

Upvotes: 8

Related Questions