Linux bash脚本可能需要root权限

Linux bash脚本可能需要root权限,linux,bash,permissions,root,Linux,Bash,Permissions,Root,我正在努力学习bash脚本。我编写了一个脚本,将文件名中的空格转换为下划线。没问题。到目前为止还不错 我的脚本可能会进入某个目录,其中包含其他用户拥有的文件,例如root或www数据 幸运的是,我的脚本无法转换这些文件:但我更喜欢一条警告消息,比如您需要root权限等等 该转换块: if [[ $# -eq 2 ]]; then echo "Converting directory $2 .." find . -name '* *' | while read file

我正在努力学习bash脚本。我编写了一个脚本,将文件名中的空格转换为下划线。没问题。到目前为止还不错

我的脚本可能会进入某个目录,其中包含其他用户拥有的文件,例如root或www数据

幸运的是,我的脚本无法转换这些文件:但我更喜欢一条警告消息,比如您需要root权限等等

该转换块:

if  [[ $# -eq 2 ]]; then
    echo "Converting directory $2 .."
    find . -name '* *' | while read file
    do
        target=`echo "$file" | sed 's/ /_/g'`
        mv "$file" "$target" 2> /dev/null
    done
else
    fOptionE (produces usage message)
fi

你能帮我找到一个正确的方法来返回一个需要根权限的输出吗

您是否已授予脚本执行权限

chmod u+x your_script.sh
./your_script.sh

尝试查看文件是否可写:

if [ ! -w "$file" ]
then
  echo "The file is NOT writable"
else
  echo "The file is writable"
fi
试试这个:

if [ x"`whoami`"x != x"root"x ]
then
    : # do something
fi

删除2>/dev/null以使mv write有用、规范的错误消息。这比声称您需要root要好,因为mv可能会失败还有许多其他原因。如果您想检查是否需要root,可以尝试手动检查权限,但这不一定是一件简单的正确操作。