bashunixabsolute-path

Type a command that will print the absolute path to the `ls` program on your system


I am looking for a very simple command to print the absolute path of ls. I have tried a lot of different methods and can't seem to find the correct answer. The code is meant to be along the line of cd; pwd If anyone could help me out I'd be very happy! Thank you!

A few of my unsuccessful attempts:

ls pwd
ls; pwd
ls $PWD
cd; ls pwd

Solution

  • In Bash, run type -p ls. For example, on my system:

    $ type -p ls
    /bin/ls
    

    If it has to work not only in Bash, but in any POSIX shell, run command -v ls:

    $ command -v ls
    /bin/ls
    

    Alternatively, if command -v ... doesn't work, run this (without the leading $):

    $ (U="$(type ls)"; U="${U#*/}/"; echo "${U%)}")
    /bin/ls
    

    All approaches above use the shell built-ins type or command. These builtins are available in Bash and many other similar shells. They don't need any other (external) command to be installed.