检查文件是否可读可写

Jus*_*tin 22 permissions bash

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

任何提示?

mur*_*uru 35

你不需要检查它是否存在,检查读写权限就足够了:

来自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.
Run Code Online (Sandbox Code Playgroud)

所以你可以试试:

-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.
Run Code Online (Sandbox Code Playgroud)

  • @Videonauth 参见 https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs,`[[` 中允许使用 `&&` 等 (3认同)
  • 不应该是`if [[ -r $FILE ]] && [[ -w $FILE ]]` 而不是`if [[ -r $FILE && -w $FILE ]]`? (2认同)