26

I'm trying to write a script that will look for a certain .txt file saved to my desktop. I want the script to be able to check if this file exists and then check to see if it is readable and writable.

Any hints?

0

3 Answers 3

44

You needn't check if it exists, the checks for read and write permissions are enough:

From help test, a selection of relevant tests:

-a FILE        True if file exists.
-e FILE        True if file exists.
-f FILE        True if file exists and is a regular file.
-r FILE        True if file is readable by you.
-s FILE        True if file exists and is not empty.
-w FILE        True if the file is writable by you.

So you can try:

FILE="/path/to/some/file"

if [[ -r $FILE && -w $FILE ]]; then
  # do stuff
else
  # file is either not readable or writable or both
fi
2
3
test -r file.txt -a -w file.txt
echo $?

The return code is 0 if it is both readable and writeable.

1

On some network protocols, file permssion might be reported wrong, and -r fails.

Use head -c1 or dd bs=1 count=1 to check readability.

is_readable(){
    head -c1 "$1" > /dev/null 2>&1
    return $?
}

if is_readable "$file"; then
    echo "$file is readable"
else
    echo "$file is not readable"
fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .