4

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

#!/bin/bash

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

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

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
11

GNU coreutils has the realpath command that does just that.

/tmp/a$ realpath ..
/tmp

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

/tmp/b/c$ realpath ..
/tmp/x/y

(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
3

A few ideas:

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

parent="$(
   cd ..
   pwd
)"
1

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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