Softpanorama

Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
May the source be with you, but remember the KISS principle ;-)
Skepticism and critical thinking is not panacea, but can help to understand the world better

dirname function

News Recommended Books Recommended Links basename function dirname

Using -exec option with find

xargs Command Tutoria bash Tips and Tricks Admin Horror Stories Unix History Humor

Etc

There are two command in Unix that allow to parse the fully qualified file name: dirname and basename. One extract path, the other file name.

Code:
dirname "/home/one/two/three/myfile.txt"

Code:

echo "/home/one/two/three/myfile.txt" | sed 's|\(.*\)/.*|\1|'

Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

Bash script - how to get 'basename' command to do what I want..

Bash script - how to get 'basename' command to do what I want..?(SOLVED)
Hi script guru's..

Posted this earlier on the "Non-*NIX" section of this forum, but felt that I might get more response in this section instead - sorry for double posting..!!

I need some help with my script..(duh)..

I'm having trouble trying to work out how to use the "basename" command to perform what I want..

Here's the section of my script that needs review:

Code:

#---------------------------------
#           Decoding
#---------------------------------
else  # if [ "$a" == "bfe" ]
Xdialog --screen-center --wrap --no-buttons --title "INFO" --infobox "Decoding file.!" 160x50 2000 >&1
wait1
bcrypt $FILE < "$FIL2" 2>/dev/null
 if [ $? -eq 1 ];then
   error2
 else
 Xdialog --screen-center --wrap --no-buttons --title "INFO" --infobox "Pass 1 completed.!" 180x50 2000 >&1
 wait1
 FILE=`basename "$FILE" .bfe` 
 mv "$FILE" `basename "$FILE" .bfx`.bfe
 wait1
 pkey1
 wait1 
 bcrypt `basename "$FILE" .bfx`.bfe < "$input" 2>/dev/null
  if [ $? -eq 1 ];then
    erpkey
    bcrypt `basename "$FILE" .bfx`.bfe < "$input1" 2>/dev/null
    if [ $? -eq 1 ];then
      error3
    else
      echo "OK"
      Xdialog --screen-center --wrap --no-buttons --title "INFO" --infobox "Decoding completed.!" 180x50 3000 >&1
      rm -f $input
      rm -f $input1
      exit 0
    fi
  else
    rm -f $input
    Xdialog --screen-center --wrap --no-buttons --title "INFO" --infobox "Decoding completed.!" 180x50 3000 >&1
    exit 0
  fi
 fi
fi
The 'wait1' 'error2' 'pkey1' 'erpkey' 'error3' 'opcanc' are internal functions which are defined at the top of the main script..

Here is the 'error3' function that I would like to change :

Code:

function error3 {
Xdialog --screen-center --title "ERROR" --msgbox "Still incorrect personal encryption key.\n\
Please ensure that the correct Personal key is used..\n\n\
Select OK to continue.." 400x160
  if [ $? -eq 1 ];then
   opcanc
  else  
   echo "OK"
   # need to add code to handle 're-encrypting' back to original file..
   rm -f $input
   rm -f $input1
  fi
}
----------------------------------------------------------------------------------
As whole of the script actually works very well - thanks to various friendly script guru's from other forums who helped with my niggling "bash scripting" questions..
----------------------------------------------------------------------------------

Now where I would like to make the changes is in fact in the 'error3' code - but based on the section of the main script that calls it:

Code:

bcrypt `basename "$FILE" .bfx`.bfe < "$input" 2>/dev/null
  if [ $? -eq 1 ];then
    erpkey
    bcrypt `basename "$FILE" .bfx`.bfe < "$input1" 2>/dev/null
    if [ $? -eq 1 ];then
      error3
    else
      echo "OK"
    fi

Bash variable substitution vs dirname and basename

Stack Overflow

The next script

str=/aaa/bbb/ccc.txt
echo "str: $str"
echo ${str##*/} == $(basename $str)
echo ${str%/*} == $(dirname $str)

produces:

str: /aaa/bbb/ccc.txt
ccc.txt == ccc.txt
/aaa/bbb == /aaa/bbb

The question is:

Asking mainly because:

str="/aaa/bbb/ccc.txt"
count=10000

s_cmdbase() {
let i=0
while(( i++ < $count ))
do
    a=$(basename $str)
done
}

s_varbase() {
let i=0
while(( i++ < $count ))
do
    a=${str##*/}
done
}

s_cmddir() {
let i=0
while(( i++ < $count ))
do
    a=$(dirname $str)
done
}

s_vardir() {
let i=0
while(( i++ < $count ))
do
    a=${str%/*}
done
}

time s_cmdbase
echo command basename
echo ===================================
time s_varbase
echo varsub basename
echo ===================================
time s_cmddir
echo command dirname
echo ===================================
time s_vardir
echo varsub dirname

on my system produces:

real    0m33.455s
user    0m10.194s
sys     0m18.106s
command basename
===================================

real    0m0.246s
user    0m0.237s
sys     0m0.007s
varsub basename
===================================

real    0m30.562s
user    0m10.115s
sys     0m17.764s
command dirname
===================================

real    0m0.237s
user    0m0.226s
sys     0m0.007s
varsub dirname

Calling external programs (forking) costs time. The main point of the question is:

I would say: dirname and basename are tools for very precise cases like this. Variable substitutions are for more general cases. So I would use dirname whenever I want the dir name, basename when I want the file name and variable substitutions whenever I need more general things that do not have a specific tool to get. – fedorqui Mar 14 '14 at 9:39

@fedorqui I would argue that dirname and basename are easier to read, especially for people who don't code shell on a daily basis (so that's a maintenance +1) but the performance difference is a fair point. I'd argue that as soon as you need them inside a loop (and not just on $0) you will want to consider using parameter substitution. – Adrian Frühwirth Mar 14 '14 at 10:11

===

The external commands make some logical corrections. Check the result of the next script:
doit() {
    str=$1
    echo -e "string   $str"
    cmd=basename
    [[ "${str##*/}" == "$($cmd $str)" ]] && echo "$cmd same: ${str##*/}" || echo -e "$cmd different \${str##*/}\t>${str##*/}<\tvs command:\t>$($cmd $str)<"
    cmd=dirname
    [[ "${str%/*}"  == "$($cmd $str)" ]] && echo "$cmd  same: ${str%/*}" || echo -e "$cmd  different \${str%/*}\t>${str%/*}<\tvs command:\t>$($cmd $str)<"
    echo
}

doit /aaa/bbb/
doit /
doit /aaa
doit aaa
doit aaa/
doit aaa/xxx

with the result

string   /aaa/bbb/
basename different ${str##*/}   ><          vs command: >bbb<
dirname  different ${str%/*}    >/aaa/bbb<  vs command: >/aaa<

string   /
basename different ${str##*/}   ><  vs command: >/<
dirname  different ${str%/*}    ><  vs command: >/<

string   /aaa
basename same: aaa
dirname  different ${str%/*}    ><  vs command: >/<

string   aaa
basename same: aaa
dirname  different ${str%/*}    >aaa<   vs command: >.<

string   aaa/
basename different ${str##*/}   ><  vs command: >aaa<
dirname  different ${str%/*}    >aaa<   vs command: >.<

string   aaa/xxx
basename same: xxx
dirname  same: aaa

One of most interesting results is the $(dirname "aaa"). The external command dirname correctly returns . but the variable expansion ${str%/*} returns the incorrect value aaa.

Alternative presentation

Script:

doit() {
    strings=( "[[$1]]"
    "[[$(basename "$1")]]"
    "[[${1##*/}]]"
    "[[$(dirname "$1")]]"
    "[[${1%/*}]]" )
    printf "%-15s %-15s %-15s %-15s %-15s\n" "${strings[@]}"
}


printf "%-15s %-15s %-15s %-15s %-15s\n" \
    'file' 'basename $file' '${file##*/}' 'dirname $file' '${file%/*}'

doit /aaa/bbb/
doit /
doit /aaa
doit aaa
doit aaa/
doit aaa/xxx
doit aaa//

Output:

file            basename $file  ${file##*/}     dirname $file   ${file%/*}     
[[/aaa/bbb/]]   [[bbb]]         [[]]            [[/aaa]]        [[/aaa/bbb]]   
[[/]]           [[/]]           [[]]            [[/]]           [[]]           
[[/aaa]]        [[aaa]]         [[aaa]]         [[/]]           [[]]           
[[aaa]]         [[aaa]]         [[aaa]]         [[.]]           [[aaa]]        
[[aaa/]]        [[aaa]]         [[]]            [[.]]           [[aaa]]        
[[aaa/xxx]]     [[xxx]]         [[xxx]]         [[aaa]]         [[aaa]]        
[[aaa//]]       [[aaa]]         [[]]            [[.]]           [[aaa/]] 

string - Extract filename and extension in Bash - Stack Overflow

Extract filename and extension in Bash >

Oops! I didn't mean to do this. up vote744down votefavorite

398 I want to get the filename (without extension) and the extension separately.

The best solution I found so far is:

NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`

This is wrong because it doesn't work if the file name contains multiple "." characters. If, let's say, I have a.b.js it will consider a and b.js, instead of a.b and js.

It can be easily done in Python with

file, ext = os.path.splitext(path)

but I'd prefer not to fire a Python interpreter just for this, if possible.

Any better ideas?

bash string filenames

This question explains this bash technique and several other related ones. – jjclarkson Jun 12 '09 at 20:34

When applying the great answers below, do not simply paste in your variable like I show here Wrong: extension="{$filename##*.}" like I did for a while! Move the $ outside the curlys: Right: extension="${filename##*.}"Chris K Aug 7 '13 at 18:51 add a comment |

30 Answers 30

votes
up vote1501down voteaccepted First, get file without path:
filename=$(basename "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"

Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:

filename="${fullfile##*/}"
improve this answer
edited Feb 11 '14 at 17:00

polymathcoder
6315
answered Jun 8 '09 at 14:05

Petesh
39.7k33860
Check out gnu.org/software/bash/manual/html_node/… for the full feature set. – D.Shawley Jun 8 '09 at 14:08
17
Add some quotes to "$fullfile", or you'll risk breaking the filename. – lhunath Jun 8 '09 at 14:34
30
Heck, you could even write filename="${fullfile##*/}" and avoid calling an extra basenameephemient Jun 9 '09 at 17:52
13
This "solution" does not work if the file does not have an extension -- instead, the whole file name is output, which is quite bad considering that files without extensions are omnipresent. – nccc Jul 1 '12 at 3:42
62
I wish I could upvote each time I fall back on this answer because I can't remember. – Boris Guéry Jan 23

extract directory from file path

  1. Database Administrator

    Database Bot
    Join Date
    Sep 2009
    Posts
    1,234,884
    Rep Power
    1240

    extract directory from file path

    I'm writing a bash shell script and need to extract a directory from
    current path.

    Let's say I have this file name:
    /a/b/c/d/e/f/g/file.txt

    I'm looking for certain directory in the path, for example "d". If "d"
    exists I need to know the directory
    that follows it, in the example above "e".

    The script will basically loop through a large file depository, search
    for a certain directory in file path,
    and pass along child directory to a custom utility. So I need to hold
    the child directory in a variable.

    I could do that relatively easy in a perl script, but this should be
    doable in bash. Any advice?

    Reply With Quote


  2. 11-04-2008 02:56 PM #2

    Database Administrator

    Database Bot
    Join Date
    Sep 2009
    Posts
    1,234,884
    Rep Power
    1240

    Re: extract directory from file path

    Sharkie wrote:
    > I'm writing a bash shell script and need to extract a directory from
    > current path.
    >
    > Let's say I have this file name:
    > /a/b/c/d/e/f/g/file.txt
    >
    > I'm looking for certain directory in the path, for example "d". If "d"
    > exists I need to know the directory
    > that follows it, in the example above "e".

    path=/a/b/c/d/e/f/g/file.txt
    case ${path} in
    */d/*) dir=${path#*/d/} ; echo ${dir%%/*} ;;
    esac

    You can also replace the pattern /d/ by a variable if you like.

    Janis

    >
    > The script will basically loop through a large file depository, search
    > for a certain directory in file path,
    > and pass along child directory to a custom utility. So I need to hold
    > the child directory in a variable.
    >
    > I could do that relatively easy in a perl script, but this should be
    > doable in bash. Any advice?

    Reply With Quote


  3. 11-05-2008 05:38 PM #3

    Database Administrator

    Database Bot
    Join Date
    Sep 2009
    Posts
    1,234,884
    Rep Power
    1240

    Re: extract directory from file path

    On Nov 4, 12:56*pm, Janis Papanagnou
    wrote:
    >
    > path=/a/b/c/d/e/f/g/file.txt
    > case ${path} in
    > */d/*) dir=${path#*/d/} ; echo ${dir%%/*} ;;
    > esac
    >
    > You can also replace the pattern /d/ by a variable if you like.

    Thanks Janis - works perfectly. Since I didn't really understood how
    this works I searched for manipulating
    strings in bash and found this excellent site:

    http://www.museum.state.il.us/ismdep...ipulation.html

    the substring removal section describes the # and % operators quite
    well. Thanks again.

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Top articles

Sites

...

HowTo Bash Extract Filename And Extension In Unix - Linux



Etc

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2018 by Dr. Nikolai Bezroukov. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March, 12, 2019