[英]BASH for loop to test list for username
對於此特定問題,我需要編寫一個腳本來檢查列表是否存在,檢查該列表以查看是否存在通過命令行指定的用戶名,如果不存在,則將其追加到列表中。 我已經看到類似的問題,但還沒有找到專門使用for循環的問題。 我剛開始學習BASH,所以任何幫助或朝正確方向的推動都將大有幫助。 這是我到目前為止(語法錯誤)
#! /bin/bash
user=$1
if [ list.txt -f ]; then
echo "The list does not exist"
for v in $(cat list.txt)
do
if [ $v -eq $user ]; then
echo "That username already exists!"
elif
echo $user >> list.txt ; then
else echo "That file does not exist"
fi
這是您的代碼的另一種方法:
#!/bin/bash
user=$1
if [ ! -f "list.txt" ]; then
echo "The list does not exist."
else
for v in $(cat list.txt)
do
# user found
if [ "$v" = "$user" ]; then
echo "That username already exists!"
exit $?
fi
done
fi
# user not found
echo $user >> "list.txt"
關於Bash的注意事項:
=
運算符( 請參見此列表 )。 " "
)(如果文件名帶有空格等,則不是一個壞主意) elif
需要有一個條件( 請參閱此頁面並搜索elif
)。 希望這有所幫助; 知道Bash會非常有用!
循環適用於無所事事的人。
if [ -f list.txt ] && grep -q -x -F "$user" list.txt
then
echo "Username exists"
else
echo "$user" >> list.txt
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.