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?
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
test -r file.txt -a -w file.txt
echo $?
The return code is 0 if it is both readable and writeable.