views:

45

answers:

3

Hi all,

I am trying to get file extension for a file in shell script. But without any luck.

The command I am using is

file_ext=${filename##*.}

and

file_ext = $filename |awk -F . '{if (NF>1) {print $NF}}'

But both of the commands failed to put value in variable file_ext. But when i try

echo $filename |awk -F . '{if (NF>1) {print $NF}}'

It gives me the desired result. I am new to shell script. Please describe the situation what is happening. And also how should I do it?

Thanks.

+2  A: 

You have to be careful when declaring variables.

variable1="string"    # assign a string value
variable3=`command`   # assign output from command
variable2=$(command)  # assign output from command

Notice that you cannot put a space after the variable, because then it gets interpreted as a normal command.

Otto Allmendinger
Thanks well interpreted. :) . I got your point will never do this mistake.
vijay.shad
+2  A: 

Spaces hurts.

Anyway you should do:

file_ext=$(echo $filename |awk -F . '{if (NF>1) {print $NF}}')

That will store in $file_ext the output of the command.

Enrico Carlesso
Yes. The idea was to the command in $(). Thanks for your answer.
vijay.shad
You're welcome.
Enrico Carlesso
A: 

to get file extension, just use the shell

$ filename="myfile.ext"
$ echo ${filename##*.}
ext
$ file_ext=${filename##*.} #put to variable
$ echo ${file_ext}
ext
ghostdog74