readlink -f alternative in Linux 2.4

1k Views Asked by At

I have an java application.And I call some batch files from app. A batch file get full path of itself by using readlink -f. But I get "command not found error" in Linux.(Linux 2.4.18-3custom #2 Wed Aug 18 03:46:33 EDT 2004). I tried pwd command in batch file.But it gave my app current directory.But I need to find batch directory from itself.So,pwd does not solve my problem. I actually write my batch file on shell script. And I can not install coreutils. Is there any alternative for readlink -f which does not include pwd?

2

There are 2 best solutions below

7
On

This is an example forwarded solution from my dormant blog in Linuxquestions.org. You can make your script use this to get the absolute path of a path. This one works with any version of Bash. You can also get other solutions for other shells even old ones. Just check the post.

function getabspath {
    local -a T=()
    local -i I=0
    local IFS=/ A

    case "$1" in
    /*)
        __=$1
        ;;
    *)
        __=/$PWD/$1
        ;;
    esac

    while read -r -d / A; do
        case "$A" in
        ..)
            [[ I -ne 0 ]] && unset T\[--I\]
            continue
            ;;
        .|'')
            continue
            ;;
        esac

        T[I++]=$A
    done << .
$__/
.

    case "$1" in
    */)
        [[ I -ne 0 ]] && __="/${T[*]}/" || __=/
        ;;
    *)
        [[ I -ne 0 ]] && __="/${T[*]}" || __=/.
        ;;
    esac
}

Usage:

getabspath your/path/here
<Do something with "$__">

Consider compiling a simple C solution as well.

2
On

readlink is part of the coreutils package for Linux. So simply install coreutils on your system and you will have readlink available.