對所有資料夾執行 chown 並將擁有者設定為資料夾名稱減去尾隨 / 的腳本

對所有資料夾執行 chown 並將擁有者設定為資料夾名稱減去尾隨 / 的腳本

有些麻木地跑了chown -R username。在我們網頁伺服器上的 /home 資料夾中,認為他位於所需的資料夾中。不用說,伺服器正在拋出很多不穩定的東西。

我們有 200 多個網站,我不想單獨對它們進行 chown,因此我嘗試製作一個腳本,將所有資料夾的所有者更改為資料夾名稱,而無需尾隨 /。

到目前為止,這就是我所擁有的一切,一旦我可以刪除 / 就可以了,但我還想檢查該文件是否包含 . ,如果沒有,則執行該命令,否則轉到下一個。

#!/bin/bash
for f in *

do

    test=$f;
    #manipluate the test variable
    chown -R $test $f

done

任何幫助都會很棒!

先致謝!

答案1

假如說全部/home/目錄下的資料夾代表使用者名,可使用:

for dir in /home/*/; do
    # strip trailing slash
    homedir="${dir%/}"
    # strip all chars up to and including the last slash
    username="${homedir##*/}"

    case $username in
    *.*) continue ;; # skip name with a dot in it
    esac

    chown -R "$username" "$dir"
done

我建議之前執行一個測試循環,檢查使用者名稱是否確實與主目錄相符。

此 AWK 指令會擷取給定使用者的主目錄。

awk -F: -v user="$username" '{if($1 == user){print $6}}' < /etc/passwd

對照現有主目錄檢查此結果是讀者的一項練習。

答案2

您可以使用基本名稱提供路徑最後一個組成部分的命令

for dir in /home/*
do
    if [ -d "$dir" ]
    then
        username=$(basename "$dir")
        chown -R "$username" "$dir"
    fi
done

雖然我最初會將其運行為

for dir in /home/*
do
    if [ -d "$dir" ]
    then
        username=$(basename "$dir")
        echo "chown -R $username $dir"
    fi
done

以確保它是理智的。

相關內容