检查文件以及它是否可读可写


17

我正在尝试编写一个脚本,该脚本将查找保存到桌面的某个.txt文件。我希望脚本能够检查此文件是否存在,然后检查它是否可读可写。

有什么提示吗?


阅读手册中的Bash条件表达式,并使用-r-w运算符
glenn jackman 2014年

Answers:


28

您无需检查它是否存在,检查读写权限就足够了:

从中help test选择相关测试:

-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.

因此,您可以尝试:

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
不应该if [[ -r $FILE ]] && [[ -w $FILE ]]代替if [[ -r $FILE && -w $FILE ]]吗?
Videonauth

1
@Videonauth参见gnu.org/software/bash/manual/bash.html#Conditional-Constructs&&等等被允许在[[
muru
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.