|
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 |
News | Recommended Books | Recommended Links | basename function | dirname | |
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.
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
|
Switchboard | ||||
Latest | |||||
Past week | |||||
Past month |
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 fiThe '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
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/bbbThe question is:
- In bash scripts, when is it recommended to use commands dirname and basename and when the variable substitutions and why?
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 dirnameon 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 dirnameCalling external programs (forking) costs time. The main point of the question is:
- Are there some pitfalls using variable substitutions instead of external commands?
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/xxxwith 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: aaaOne 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/]]
Google matched content |
...
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 quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard 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 DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting 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-Month : How 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