bash脚本可能需要root权限
问题描述:
我正在尝试学习bash脚本。我写了一个脚本,将空格转换为文件名中的下划线。它工作正常。到现在为止还挺好。bash脚本可能需要root权限
我的脚本可能会进入某个目录,其中包含另一个用户拥有的文件(例如root或www-data)。
我的脚本无法幸运地转换这些文件:)但我更喜欢警告消息,如“您需要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
你能帮我找到返回一个“需要root权限”输出一个适当的方式?
答
你给了执行权限脚本
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'写出有用的,规范的错误信息。这比声称你需要root更好,因为mv可能会失败的原因还有很多。 – 2014-10-28 21:50:14
如果您想检查“需要root”,您可以尝试手动检查权限,但这不一定是正确执行的简单事情。 – 2014-10-28 22:25:10