How to extract filename and extension in bash shell script

#!/bin/bash
# get file name only without path
file_name=$(basename $BASH_SOURCE)
# get extension
file_extension="${file_name##*.}"
# get file name without extension
file="${file_name%.*}"
# print them to verify
echo "Full input file : $BASH_SOURCE"
echo "Filename only : $file_name"
echo "File extension only: $file_extension"
echo "First part of filename only, without extension: $file"
[ec2-user@dockers ~]$ bash ~/test.sh
Full input file : /home/ec2-user/test.sh
Filename only : test.sh
File extension only: sh
First part of filename only, without extension: test

Comments