2014-10-28 107 views
1

我正在嘗試學習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權限」輸出一個適當的方式?

+1

刪除'2>/dev/null'使'mv'寫出有用的,規範的錯誤信息。這比聲稱你需要root更好,因爲mv可能會失敗的原因還有很多。 – 2014-10-28 21:50:14

+0

如果您想檢查「需要root」,您可以嘗試手動檢查權限,但這不一定是正確執行的簡單事情。 – 2014-10-28 22:25:10

回答

0

你給了執行權限腳本

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

嘗試看看,如果該文件是可寫的:

if [ ! -w "$file" ] 
then 
    echo "The file is NOT writable" 
else 
    echo "The file is writable" 
fi 
0

試試這個:

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