views:

421

answers:

2

Given file names like these:

/the/path/foo.txt
bar.txt

I hope to get

foo
bar

Why this doesn't work?

#!/bin/bash

fullfile=$1
fname=$(basename $fullfile)
fbname=${filename%.*}
echo $fbname

What's the right way to do it?

+4  A: 

because you are using the wrong variable. It should be fname, not filename. Anyway, you don't have to call external basename command

$ s=/the/path/foo.txt
$ echo ${s##*/}
foo.txt
$ s=${s##*/}
$ echo ${s%.txt}
foo
$ echo ${s%.*}
foo
ghostdog74
+3  A: 

The basename command has two different invocations; in one, you specify just the path, in which case it gives you the last component, while in the other you also give a suffix that it will remove. So, you can simplify your example code by using the second invocation of basename. Also, be careful to correctly quote things:

fbname=`basename "$1" .txt`
echo "$fbname"
Michael Aaron Safyan