Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do [ -r $1 ] and [ ! -r $1 ] mean in Bash?

Tags:

bash

I learned that -r means recursive, which means the command can be performed in all subdirectories. To make sure I understand, I wrote the two functions below to make some tests. The file where I wrote the following code was named as test.sh. Inside the same directory I have a sub-directory called subtest. There's a file named xx.sh either in the current directory of in the sub-directory.

#!/bin/bash
function aa {
  if [ ! -r $1 ]
  then
    echo "not exist"
  else
    echo "exist"
  fi
}

function bb {
  if [ -r $1 ]
  then
    echo "exist"
  else
    echo "not exist"
  fi
}

aa xx.sh / bb xx.sh

The results I found:

For aa function, with -r, it will only print "exist" if xx.sh is in the current directory. It won't look for xx.sh in the sub-directory. Without -r, it will print "exist" when xx.sh is either in current directory or in the subdirectory.

For bb function, with -r, it will only print "exist" when the current directory has xx.sh. Without -r, it will always print "exist", even if there is no xx.sh at all (which surprised me and does not make sense!).

Can anyone explain why the results above happen and what does -r do exactly?

like image 404
Consideration Avatar asked Dec 07 '25 05:12

Consideration


1 Answers

My documentation for the conditional (and this is what you are looking for, since it is within [ and ]) reads:

 -r file
              True if file exists and is readable.
like image 193
Michael Piefel Avatar answered Dec 09 '25 00:12

Michael Piefel



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!