0

given the bash code below, i am defining a variable to represent a folder and i am checking if it is a folder. I can even browse into it using the variable name.

There is a small catch here, i defined the folder's name with '/' as the last character, because the tab completion completes the string this way.

#! /bin/bash


VAR_LOG='/var/log/'


echo $VAR_LOG
echo $PWD

echo "browsing to log directory"
cd $VAR_LOG
echo $PWD


if [ -d $VAR_LOG ]; then
    echo "$VAR_LOG is a directory"
fi

if [ ${VAR_LOG} != ${PWD} ]
then echo not same
else 
echo same
fi

But as you can see, $PWD defines the same path/folder without '/' as the last character and the string comparison will result as false. Even though i am in the same folder and the cd $LOG_DIR will take me to the same folder.

User1-MBP:log User1$ $HOME/tmp.sh 
/var/log/
/Users/User1
browsing to log directory
/var/log
/var/log/ is a directory
not same

So, what is the best way to work with directories in bash? Keeping them as strings is somewhat error-prone.

(NOTE: this is a MacOS system - i am not sure if it should make any difference)

Thanks a lot..

jww
  • 97,681
  • 90
  • 411
  • 885

1 Answers1

0

If you only care about string equality, you can strip the trailing \ from VAR_LOG by using ${VAR_LOG%/} expansion (Remove matching suffix pattern). This will strip one (last / from VAR_LOG if present and leave it unchanged when not:

if [ "${VAR_LOG%/}" != "${PWD}" ]; ...

However, you can also (and probably should) use -ef test:

FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers

I.e.:

if [ ! "${VAR_LOG}" -ef "${PWD}" ]; ...

Ensure both file/directory names refer to the same file.

This is not relevant for directories, but different filenames referring to the same inode (hardlinks) would evaluate to 0 on -ef test.

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39