Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

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

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

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-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) 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 to buy a cup of coffee for authors of this site

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 Softpanorama society. 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