简体   繁体   中英

BASH for loop to test list for username

For this specific problem I need to write a script that checks for the existence of a list, checks the list to see if the username given through the command line exists and if it doesn't, it appends it to the list. I've seen similar questions like this but haven't found one that specifically uses the for loop. I just started learning BASH the other day so any help or a push in the right direction will be of great help. Here is what I have so far (with syntax errors)

#! /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

Here is another approach to your code:

#!/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"

Notes on Bash:

  • When comparing strings in bash, you'll want to use the = operator ( see this list ).
  • Not a bad idea to use quotes ( " " ) for file names (in case the file names have spaces, etc.)
  • elif needs to have a condition, if you are going to use it ( see this page and search for elif ).

Hope this helps a little; knowing Bash can be pretty useful!

Loops are for people with nothing better to do.

if [ -f list.txt ] && grep -q -x -F "$user" list.txt
then
  echo "Username exists"
else
  echo "$user" >> list.txt
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM