I have a script which finds files in the directory specified by user.


# make sure about the correct input
if [ -z $1 ]
    echo "Usage: ./script_name.sh    path/to/directory"
    if [ $DIR = '.' ]
        echo "Find files in the directory $PWD"
        echo "Find files in the directory $DIR"

    find $DIR -type f -exec basename {} \; 

if I input

$ ./script_name.sh .

script gives me correct substitution ./ to $PWD and shows (for example)

$ Find files in the directory /root/scripts  

But I can't make a decision how to substitute ../ to the name of the directory immediately above in the hierarchy. If I input

$ ./script_name.sh ..  

script gives me the output

$ Find files in the directory ..  

Does anybody know how to substitute ../ to the actual name of the directory?

  • Try the realpath command if it is available. – Bodo Feb 19 at 14:33
  • @Bodo realpath works good in this case. – Alex Kuchin Feb 19 at 14:59

GNU coreutils has the realpath command that does just that.

/tmp/a$ realpath ..

Though note that if the path contains symlinks, it will also resolve those:

/tmp/b/c$ realpath ..

(Here, /tmp/b was a symlink to /tmp/x/y/)

This may be different from what the shell does with cd ... E.g. cd ../.. from /tmp/b/c in Bash shows the new path as /tmp/, not as /tmp/x.

  • readlink would be another alternative. – twalberg Feb 19 at 16:55
  • @twalberg readlink only resolves symlinks and not entries like . or .., which were the point of the question. readlink . results in an error (returns status code 1). – JoL Feb 19 at 18:43
  • 4
    @JoL Try readlink -f . – twalberg Feb 19 at 18:44

A few ideas:

parent="$(dirname "$(pwd)")"

   cd ..

You could first cd to .. and then use the $PWD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.