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
if [[ -r $FILE ]] && [[ -w $FILE ]]
instead of if [[ -r $FILE && -w $FILE ]]
?
Nov 27, 2017 at 10:21
&&
etc are allowed in [[
test -r file.txt -a -w file.txt
echo $?
The return code is 0 if it is both readable and writeable.
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