简体   繁体   中英

Bash basename syntax

I'm trying to write a script that takes the basename of an argument, then checks if there is an extension in that argument. If there is, it prints the extension.

Here is my code:

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

I'm echoing the final $basename $1 to check what the output of basename is.

Some tests reveal:

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

So neither $basename $1 are working. I know it's a syntax error so could someone explain what I'm doing wrong?

EDIT:

I've solved my problem now with:

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

Which reduces my argument to a basename, thank you all.

First, your syntax is wrong:

file=$( basename "$1" )

Second, this is the correct expression to get the file name's (last) extension:

ext=${file##*.}

If you want to assign to a variable the output of a command, you must execute it, either with back quotes or using a special parenthesis quoting:

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

To remove a filename's extension you should do

ext=${file#*.}

this will get the value of $file , then remove everything up to the period (that's why it is necessary). If your filename contains periods, then you should use ext=${file##*.} , where the ## tells bash to delete the longest string that matches instead of the shortest, so it will delete up to the last period, instead of the first one.

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

If you want to print the command you're trying to execute, do this:

echo basename $1

If you're trying to print the output of the command, you can do one of:

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

Hope this helps =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM