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

basename 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

The absolute path (path from the root directory) to any Unix file consists of two components: path and basename. Linux has three commands for to parse the absolutes path (also called FQN -- fully qualified name) into two components. 

Actually it is not necessary to be absolute path, relative path will be parsed as well. The basename command examines a path and displays the filename. It doesn't check to see whether the file exists.

basename /home/joeuser/www/robots.txt
robots.txt

If a suffix is included as a second parameter, basename deletes the suffix if it matches the file's suffix.

$ basename /home/joeuser/www/robots.txt .txt
robots

The corresponding program for extracting the path to the file is dirname.

$ dirname /home/joeuser/www/robots.txt
/home/joeuser/test

There is no trailing slash after the final directory in the path.

Using tr command and those two command you can replace blanks in a filename of any command with underscored in a following way

find /home/joeuser/ -name="*.txt" -type -f   -exec  /home/joeuser/bin/rename_windows_file.sh {}

where rename_windows_file.sh  is something like

#!/bin/bash
f=`basename $1`
d=`dirname $1`
f=`tr ' ' '_' <<< $f` 
mv $1 $d/$f

To verify that a pathname is a correct Linux pathname, you can use the pathchk command. This command verifies that the directories in the path (if they already exist) are accessible and that the names of the directories and file are not too long. If there is a problem with the path, pathchk reports the problem and returns an error code of 1.

$ pathchk "~/x" && echo "Acceptable path"
Acceptable path
$ mkdir a
$ chmod 400 a
$ pathchk "a/test.txt"

With the --portability (-p) switch, pathchk enforces stricter portability checks for all POSIX-compliant Unix systems. This identifies characters not allowed in a pathname, such as spaces.

$ pathchk "new file.txt"
$ pathchk -p "new file.txt"
pathchk: path 'new file.txt' contains nonportable character ' '

pathchk is useful for checking pathnames supplied from an outside source, such as pathnames from another script or those typed in by a user.

  1. basename  takes a suffix as second parameter which will also remove this component from the filename. You can emulate this as well using parameter substitution but since you cannot do both at once it is not as brief as when using basename.
  2. Using either dirname  or basename  require a subshell since they are not shell built-ins, so the parameter substitution will be faster, especially when calling them in a loop (as you have shown).
  3. I have seen basename  in different locations on different systems (/usr/bin, /bin) so if you have to use absolute paths in your script for some reason it might break since it cannot find the executable.

So, yes, there are some things to consider and depending on situation and input I use both methods.

EDIT: Both dirname  and basename  are actually available as bash  loadable builtins under examples/loadables  in the source tree and can be enabled (once compiled) using

enable -f /path/to/dirname dirname
enable -f /path/to/basename basename

Strip directory and suffix from filenames

Syntax
      basename NAME [SUFFIX]

      basename OPTION

Key
   --help
        Display help

   --version
        Output version information and exit

basename will print NAME with any leading directory components removed. If specified, it will also remove a trailing SUFFIX (typically a file extension).

Examples

Get the name of the home folder:

$ basename ~

Extract the file name from the variable pathnamevar and store in the variable result using parameter expansion $( )

$ result=$(basename "$pathnamevar")

A script to rename file extensions:

#BatchRenameExt
for file in *.$1; do
   mv $file `basename $file $1`.$2
done
$ BatchRenameExt htm html

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/]] 

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Top articles

Sites

...



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