Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash basename syntax

Tags:

bash

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.

like image 797
Unknown Avatar asked Oct 11 '12 16:10

Unknown


People also ask

What is basename in bash script?

In Linux, the basename command prints the last element of a file path. This is especially useful in bash scripts where the file name needs to be extracted from a long file line. The “basename” takes a filename and prints the filename's last portion. It can also delete any following suffix if needed.

What is basename $0 shell script?

Using the basename Command The $0 is a special variable in bash that represents the filename with a relative path. Hence, we've used the basename command to strip directory names from the script's filename.

What is $0 and $1 in bash?

Shell scripts have access to some "magic" variables from the environment: $0 - The name of the script. $1 - The first argument sent to the script. $2 - The second argument sent to the script.

What is the use of basename CMD?

basename strips directory information and suffixes from file names i.e. it prints the file name NAME with any leading directory components removed.


1 Answers

First, your syntax is wrong:

file=$( basename "$1" )

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

ext=${file##*.}
like image 187
chepner Avatar answered Jan 20 '23 08:01

chepner