6

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?

2
  • Try the realpath command if it is available.
    – Bodo
    Commented Feb 19, 2019 at 14:33
  • @Bodo realpath works good in this case.
    – Olek K
    Commented Feb 19, 2019 at 14:59

3 Answers 3

12

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.

3
  • readlink would be another alternative.
    – twalberg
    Commented Feb 19, 2019 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
    Commented Feb 19, 2019 at 18:43
  • 4
    @JoL Try readlink -f .
    – twalberg
    Commented Feb 19, 2019 at 18:44
3

A few ideas:

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

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .