這是我的代碼:
#!/bin/bash
function userList() {
for line in $(cat /etc/passwd)
do
USER=$(echo $line | cut -d":" -f1)
USERID=$(echo $line | cut -d":" -f3)
if (( $USERID >= 1000 ))
then
echo $USER
fi
done
}
我希望它顯示系統的所有用戶,但是每次我在終端中呼叫該函式時,它都會拋出用戶的名稱,但也會出現以下錯誤:
syntax error: operand expected (error token is "/ur/sbin/no login >= 1000 ")
uj5u.com熱心網友回復:
for line in $(cat /etc/passwd)
這不是遍歷檔案中的行,而是遍歷檔案中的單詞,其中單詞由空格、制表符或換行符分隔。當該行包含兩個單詞時,則$line變為其他內容,則echo $line | cut -d":" -f3可能不是數字。例如在這一行:
name:password:UID:GID:A comment:directory:shell
然后$line將等于name:password:UID:GID:A第一次回圈迭代,而不是comment:directory:shell第二次回圈迭代。第二次,您的腳本給出錯誤 -shell不是數字。
檢查您的腳本是否會進行 shellcheck。參考變數擴展。用于while IFS= read- r逐行讀取檔案,或者在這種情況下while IFS=: read -r逐欄位讀取。考慮閱讀有關如何撰寫基本 shell 腳本的教程,例如逐行讀取檔案。您可以閱讀有關https://mywiki.wooledge.org/BashFAQ/001的資訊。而且,考慮在 awk 中撰寫它,它只是awk -F: '$3>=1000{print $1}'.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487214.html
