現在ログインしているすべてのユーザーを表示し、各ユーザーがディレクトリに特定のファイルを持っているかどうかを示すシェルスクリプトを作成しようとしています。スクリプトを書きましたが、結果はありません!なぜそんなことですか?
#!/usr/bin/env bash
Files=$( who | cut -d' ' -f1 | sort | uniq)
for file in $FILES
do
if [ -f ~/public_html/pub_key.asc ]; then
echo "user $file : Exists"
else
echo "user $file : Not exists!"
fi
done
ベストアンサー1
各ユーザーのホームディレクトリをインポートする必要があります。すべてのユーザーのホームページが にある場合、/home/$USER
以下は簡単です。
#!/usr/bin/env bash
who | cut -d' ' -f1 | sort | uniq |
while read userName; do
file="/home/$userName/public_html/pub_key.asc"
if [ -f $file ]; then
echo "$file : Exists"
else
echo "$file : Does not exist!"
fi
done
/home/$USER
たとえば、ユーザーのHOMEでない場合は、root
まずそのホームディレクトリを見つける必要があります。次の方法でこれを実行できますgetent
。
#!/usr/bin/env bash
who | cut -d' ' -f1 | sort | uniq |
while read userName; do
homeDir=$(getent passwd "$userName" | cut -d: -f6)
file=public_html/pub_key.asc
if [[ -f "$homeDir"/"$file" ]]; then
echo "$file : Exists"
else
echo "$file : Does not exist!"
fi
done
次の問題は、ユーザーのホームディレクトリへのアクセス権がないと、ファイルが存在してもスクリプトが存在しないことを報告することです。したがって、rootとして実行することも、最初にディレクトリにアクセスできることを確認し、そうでない場合は文句を言うことができます。
#!/usr/bin/env bash
file="public_html/pub_key.asc"
who | cut -d' ' -f1 | sort | uniq |
while read userName; do
homeDir=$(getent passwd "$userName" | cut -d: -f6)
if [ -x $homeDir ]; then
if [ -f "$homeDir/$file" ]; then
echo "$file : Exists"
else
echo "$file : Does not exist!"
fi
else
echo "No read access to $homeDir!"
fi
done