Talespin_Kit
Talespin_Kit

Reputation: 21897

check if the pwd is / in bash

I am trying to write a bash script which will "cd .." until either a directory is found containing another specific directory, or the "/" directory is reached.

What I'm trying to achieve is something like:

while test -d REQUIRED_DIR || [[ "$PWD" != "/" ]];do cd ..; done

The goal is to find the REQUIRED_DIR or stop navigating when the root directory is reached.

Below is the bash code which does not work.

while if [ "$PWD"=="/" ];then echo $PWD;false;else true;fi
do
        cd ..
        #echo `pwd`
done

The if condition always passes even when not inside root directory.

UPDATE:- the "if" works as expected when i leave space b/w the "==" sign like this [ "$PWD" == "/" ].

Upvotes: 3

Views: 6008

Answers (1)

paxdiablo
paxdiablo

Reputation: 882376

while if is a new one on me, I'm not sure entirely what you're trying to achieve by combining them.

I think you may want to just try while on it's own:

while [[ "$PWD" != "/" ]] ; do
    cd ..
done

or you could just try the much simpler:

cd /

If, as indicated in your comment, you need to do it piecemeal so that you either end up in the first directory containing a $REQUIRED_DIR or / if you don't find one, you can simply do something like:

while [[ "$PWD" != "/" ]] ; do
    if [[ -d "$REQUIRED_DIR" ]] ; then
        break
    fi
    cd ..
done

Upvotes: 7

Related Questions