Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this bash -e and -L test not capture this link?

Tags:

bash

I have a bash script which is intended to be idempotent. It creates symlinks, and it should be okay if the links are already there.

Here's an extract

    L="/var/me/foo"
    if [[ -e "$L" ]] && ! [[ -L "$L" ]];
    then
        echo "$L exists but is not a link."
        exit 1;
    elif [[ -e "$L" ]] && [[ -L "$L" ]];
    then
        echo "$L exists and is a link."
    else
        ln -s "/other/place" "$L" ||
        {
            echo "Could not chown ln -s for $L";
            exit 1;
        }
    fi

The file /var/me/foo is already a symlink pointing to /other/place, according to ls -l.

Nevertheless, when I run this script the if and elif branches are not entered, instead we go into the else and attempt the ln, which fails because the file already exists.

Why do my tests not work?

like image 538
spraff Avatar asked Jan 30 '26 01:01

spraff


1 Answers

Because you only check [ -L "$L" ] if [ -e "$L" ] is true, and [ -e "$L" ] returns false for a link pointing to a destination that doesn't exist, you don't detect links that point to locations that don't exist.

The below logic is a bit more comprehensive.

link=/var/me/foo
dest=/other/place
# because [[ ]] is in use, quotes are not mandatory
if [[ -L $link ]]; then
  echo "$link exists as a link, though its target may or may not exist" >&2
elif [[ -e $link ]]; then
  echo "$link exists but is not a link" >&2
  exit 1
else
  ln -s "$dest" "$link" || { echo "yadda yadda" >&2; exit 1; }
fi
like image 96
Charles Duffy Avatar answered Jan 31 '26 16:01

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!