HowTo: Bash Extract Filename And Extension In Unix / Linux

I have setup a shell variable called dest=”/nas100/backups/servers/z/zebra/mysql.tgz”. How do I find out filename (mysql.tgz) and extension (.tgz) in bash program running under Linux or Unix operating systems?

The $ character is used for parameter expansion and command substitution. You can use it for manipulating and/or expanding variables on demands without using
Tutorial details
Difficulty level Easy
Root privileges No/Yes
Requirements Bash
Est. reading time N/A
external commands such as cut, tr, sed or awk.

Find out filename

The syntax is as follows to remove the pattern (front of $VAR):


To get file name, enter:

echo "${dest##*/}"


echo "${f}"

Sample outputs:


Find out file extension

The syntax is as follows to remove the pattern from back of $VAR:

echo "${dest##*.}"


echo "${e}"

Sample outputs:


Extract filename i.e. filename without extension

The syntax is as follows to remove the pattern from back of $VAR:


To get filename without an extension, enter:

## get file name i.e. basename such as mysql.tgz
## display filename 
echo "${tempfile%.*}"

Sample outputs:


Putting it all together

## A sample shell script to demo concept of shell parameter expansion
## Usage: backup.bash /path/to/backup.tar.gz 
## Author: nixCraft <> under GPL v2.x+
## -------------------------------------------------------------------
## Get our script name ##
## get filename from cmd arg $1
## Failsafe 
[[ $# -ne 1 ]] && { echo -en "Usage:\t$_me /path/to/file.tar\n\t$_me /path/to/file.tgz\n"; exit 1; }
## Backup these dirs 
_what="/etc /home /root"
## Get dirname 
# Get filename 
# Get file extension 
# Set tar options
# Old backup file name starts with
## Okay log data to syslog
logger "$_me backup job started at $(date)@${HOSTNAME}"
## make decision based upon file extension
[[ "$_extesion" == "tgz" ]] && { _opt="zcvf"; _oldpref="tgz"; } 
[[ "$_extesion" == "tar" ]] && { _opt="cvf"; _oldpref="tar";  } 
## Just display commands for demo purpose ##
echo "tar $_opt /tmp/${_filename} $_what"
echo "mv -f ${_backuppath} ${_dirname}/${_oldsuff}.${_filename%.*}.${_oldpref}"
echo "cp -f /tmp/${_filename} ${_backuppath}"
logger "$_me backup job ended at $(date)@${HOSTNAME}"

Run the script as follows:
backup.bash /backcup/data/server42/latest.tar
Sample outputs:

tar cvf /tmp/latest.tar /etc /home /root
mv -f /backcup/data/server42/latest.tar /backcup/data/server42/old.latest.tar
cp -f /tmp/latest.tar /backcup/data/server42/latest.tar

Again run as follows:
backup.bash /backcup/data/server42/latest.tgz
Sample outputs:

tar zcvf /tmp/latest.tgz /etc /home /root
mv -f /backcup/data/server42/latest.tgz /backcup/data/server42/old.latest.tgz
cp -f /tmp/latest.tgz /backcup/data/server42/latest.tgz

Recommend readings

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 3 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
3 comments… add one
  • Leslie Satenstein Jan 3, 2013 @ 3:27

    Use basename

    basename /tmp/other/mysql.txz

    returns to bash, mysql.txz

    basename /tmp/other/mysql.txz .txz returns mysql

  • Deniz Gezmis Jun 5, 2013 @ 2:46

    Leslie, you cannot generalize your scripts. It won’t work if you use anything other than “.txz”.

  • me Dec 11, 2013 @ 22:21

    There are not only .tgz but .tar.gz files out there. What then?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum