Checking for a file and whether it is readable and writable

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

2 Answers

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
test -r file.txt -a -w file.txt
echo $?

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like