Comments on Linux dirname Command Explained for Beginners (4 Examples)

Are you a new Linux user? Does your work involve shell scripting? If your answer to both these questions is yes, the tool we'll be discussing here will likely interest you. The name of the tool is dirname, and it's mostly used in situations where-in you need to strip the last component from an absolute file-name.

5 Comment(s)

Add comment

Please register in our forum first to comment.

Comments

By: Newbie

Could you please post a scenario where one needs 'to strip the last component from an absolute file-name'?

Many thanks.

By: till

This can be useful for bash scripting. E.g. you have the path of a file and want to store something else in the same directory.

By: Croydon

 e.g.

 

#!/bin/bash

PROG="$1"

WORKDIR=$(dirname $PROG)

cd /tmp

… run commands …

echo "Something or result from command" > ${WORKDIR}/logfile.log

By: sanjay desai

Thank you very much for sharing valuable information.I'm a novice for shell script and have to work in readymade shell script hence I need some help .what will be o/p of below shell script code ? Can you explain in brief in you don't mind.

 

PATHNAME=`dirname $0`

APPLPATH=`echo $PATHNAME | awk '{ j = length(bindir);

  k = length($0);

  st1 = sprintf("/%s",bindir);

  if (substr($0,k-j) == st1) {

     printf ("%s",substr($0,1,k-j-1))

  }

}' bindir=$APPLBIN`

 

Thanks

Sanjay

By: abc

what is the maning of the command dirname $0