[英]How to create a bash script in Linux that checks if the user is local or not
我正在嘗試創建一個提示輸入用戶名的 Linux bash 腳本。 例如,它要求輸入用戶名,一旦輸入用戶名,它就會檢查用戶是否存在。 我已經嘗試過這樣做了,但我不確定我是否做得正確。 我會很感激你的幫助。
這是我如何做到的:
#!/bin/bash
echo "Enter your username:"
read username
if [ $(getent passwd $username) ] ; then
echo "The user $username is a local user."
else
echo "The user $username is not a local user."
fi
嘗試以下腳本:
user="bob"
if cut -d: -f1 /etc/passwd | grep -w "$user"; then
echo "user $user found"
else
echo "user $user not found"
fi
文件/etc/passwd
包含本地用戶的列表以及他們的一些參數。 我們使用cut -d: -f1
僅提取用戶名,並使用grep -w $user
其與我們的用戶匹配。 if
條件評估函數的退出代碼以確定用戶是否存在。
if id "$username" >/dev/null 2>&1; then
echo "yes the user '$username' exists"
fi
或者
getent
命令旨在收集可由 /etc 文件和各種遠程服務(如 LDAP、AD、NIS/黃頁、DNS 等)支持的數據庫條目。
if getent passwd "$username" > /dev/null 2>&1; then
echo "yes the user '$username' exists"
fi
會做你的工作,例如下面
#!/bin/bash
echo "Enter your username:"
read username
if getent passwd "$username" > /dev/null 2>&1; then
echo "yes the user '$username' exists"
else
echo "No, the user '$username' does not exist"
fi
嘗試這個。
#!/bin/sh
USER="userid"
if id $USER > /dev/null 2>&1; then
echo "user exist!"
else
echo "user deosn't exist"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.