HowTo: Bash Extract Filename And Extension In Unix / Linux

by on December 14, 2012 · 3 comments· LAST UPDATED December 14, 2012

in , ,

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
DifficultyEasy (rss)
Root privilegesNo/Yes
RequirementsBash
Estimated completion timeN/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):

 
${var#Pattern}          
${var##Pattern} 
 

To get file name, enter:

 
dest="/nas100/backups/servers/z/zebra/mysql.tgz"
echo "${dest##*/}"
 

OR

 
dest="/nas100/backups/servers/z/zebra/mysql.tgz"
f="${dest##*/}"
echo "${f}"
 

Sample outputs:

mysql.tgz

Find out file extension

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

 
dest="/nas100/backups/servers/z/zebra/mysql.tgz"
echo "${dest##*.}"
 

OR

 
dest="/nas100/backups/servers/z/zebra/mysql.tgz"
e="${dest##*.}"
echo "${e}"
 

Sample outputs:

tgz

Extract filename i.e. filename without extension

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

 
${var%pattern}
${var%%pattern}
 

To get filename without an extension, enter:

 
dest="/nas100/backups/servers/z/zebra/mysql.tgz"
## get file name i.e. basename such as mysql.tgz
tempfile="${dest##*/}"
 
## display filename 
echo "${tempfile%.*}"

Sample outputs:

mysql

Putting it all together

#!/bin/bash
## A sample shell script to demo concept of shell parameter expansion
## Usage: backup.bash /path/to/backup.tar.gz 
## Author: nixCraft <www.cyberciti.biz> under GPL v2.x+
## -------------------------------------------------------------------
 
## Get our script name ##
_me="${0##*/}"
 
## get filename from cmd arg $1
_backuppath="$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 
_dirname="${_backuppath%/*}"
 
# Get filename 
_filename="${_backuppath##*/}"
 
# Get file extension 
_extesion="${_filename##*.}"
 
# Set tar options
_opt=""
 
# Old backup file name starts with
_oldsuff="old"
 
 
## 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

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 3 comments… read them below or add one }

1 Leslie Satenstein January 3, 2013 at 3:27 am

Use basename

basename /tmp/other/mysql.txz

returns to bash, mysql.txz

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

Reply

2 Deniz Gezmis June 5, 2013 at 2:46 am

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

Reply

3 me December 11, 2013 at 10:21 pm

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

Reply

Leave a Comment

Tagged as: , ,

Previous Faq:

Next Faq: