Bash basename syntax

I am trying to write a script that takes the base name of an argument and then checks if an extension exists in this argument. If there is, it prints the extension.

Here is my code:

file=basename $1 ext=${file%*} echo ${file#"$stub"} echo $basename $1 

I repeat the final $ basename $ 1 to check what basename output is.

Some tests show:

 testfile.sh one.two ./testfile: line 2: one.two: command not found one.two testfile.sh ../tester ./testfile: line 2: ../tester: No such file or directory ../tester 

Thus, neither $ basename $ 1 works. I know this is a syntax error, so can anyone explain what I'm doing wrong?

EDIT:

I solved the problem now:

 file=$(basename "$1" ) stub=${file%.*} echo ${file#"$stub"} 

Which reduces my argument to the base name, thank you all.

+7
source share
2 answers

Firstly, your syntax is incorrect:

 file=$( basename "$1" ) 

Secondly, this is the correct expression to get the file name (last):

 ext=${file##*.} 
+12
source

If you want to assign the output of a command to a variable, you must execute it either with backquotes or with a special quote:

 file=`basename "$1"` file=$(basename "$1") 

To remove the file name extension, you must do

 ext=${file#*.} 

this will get the value of $file , and then delete everything before the period (for which it is necessary). If your file name contains periods, you should use ext=${file##*.} , Where ## tells bash to delete the longest line that matches instead of the shortest, so it will be deleted until the last period, and not the first.

Your echo $basename $1 is simple. It tells bash to print the value of a variable called $basename and the value of $1 , which is the first argument to the script (or function).

If you want to print the command you are trying to execute, do the following:

 echo basename $1 

If you are trying to print the output of a command, you can do one of the following:

 echo $(basename "$1") echo "$file" basename "$1" 

Hope this helps =)

+8
source

All Articles