如何检查运行命令是否需要“sudo”权限?

Kev*_*rke 4 permissions sudo

有没有办法轻松确定我是否可以读取或写入给定文件,或者是否需要使用“sudo”来执行此操作?不必要地以 sudo 身份运行命令意味着这些文件是以 root 用户作为所有者创建的,这是不可取的。

就像是

is_readable /path/to/file
if [[ $? == 0 ]]; then
    do_command /path/to/file;
else
    sudo do_command /path/to/file;
fi
Run Code Online (Sandbox Code Playgroud)

cha*_*aos 6

您可以尝试实用程序的-w开关test

[ -w /path/to/file ] && do_command /path/to/file || sudo do_command /path/to/file
Run Code Online (Sandbox Code Playgroud)

或者长版:

if [ -w /path/to/file ]; then
  do_command /path/to/file 
else
  sudo do_command /path/to/file
fi
Run Code Online (Sandbox Code Playgroud)

联机帮助页

-w FILE
              FILE exists and write permission is granted
Run Code Online (Sandbox Code Playgroud)