0

I want to check if an external drive is still plugged in by checking /dev/disk/by-uuid/1234-5678.

However, I know that this could be done much easier with:

if ! [ -e "/non_existing_file" ]
   echo "File dont exists anymore"
fi

But I still want to know why the script in the Title dont work. Is it because of the exit code of ls?

Thanks in advance.

rjs
  • 31
  • 4

1 Answers1

0

It looks like the ls -l /nonexisting is a string that is not executed. This should work correctly if it is executed in a subshell.

Compare the example in the title:

if [[ -z "ls -l something.txt 2> /dev/null" ]]; then 
  echo "file does not exist"
fi

... with this version that returns as expected:

if [[ -z "$(ls -l something.txt 2> /dev/null)" ]]; then
  echo "file does not exist"
fi
Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34
  • 1
    Note the guidance in the *Answer Well-Asked Questions* section of [How to Answer](https://stackoverflow.com/help/how-to-answer) regarding questions that have "been asked and answered many times before". – Charles Duffy Sep 27 '20 at 19:06