dirname

In Bash, the dirname command is not found


I'm writing a simple script:

#!/bin/bash
PATH=$(readlink -f $0)
echo $PATH
DIR_PATH=$(dirname $PATH)
echo $DIR_PATH

However, the output is:

/home/kalyani/Desktop/Linux/Proj/script.sh
./script.sh:line 6: dirname: command not found

I checked every other solution available, and tried each one, and none of them worked. I've read the other threads on similar problems and it still doesn't work.

What could be the problem?

Also, if I type 'which dirname', I get /usr/bin/dirname.

If I echo $PATH, I get:

/home/kalyani/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin/:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

Since /usr/bin is in my $PATH variable, it should be found, and it is found if I type it in the terminal, but if it's in a bash script, then it's giving me trouble. What can I do?


Solution

  • As soon as you execute

    PATH=$(readlink -f $0)
    

    Your PATH is now the name of the linked file, which is not a directory, so nothing is in your PATH anymore.

    Use a different variable. If you are trying to make sure your path includes the location of the current file, the use

    me="$(readlink -f ${BASH_SOURCE:-$0})"
    PATH=$PATH:${me%/*}
    

    If you aren't using bash,

    me=`readlink -f "$0"`
    PATH="$PATH:"`dirname $me`
    

    or

    PATH="$PATH:"`readlink -f "$0" | sed 's,/[^/]*$,,'`