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.
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.
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.
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.
basename strips directory information and suffixes from file names i.e. it prints the file name NAME with any leading directory components removed.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With