简体   繁体   中英

String Bash scripting if then statement fails

I am currently writing a script that will allow me to add groups via user input. I am on the portion of my script where the user types the group name in and it compares it against /etc/group and lets the user know if it needs to be added or not. I have tested this against a group that I know for a fact is not on my system and it only reads the first statement in my loop. Could someone tell me where I am going wrong?

#!/bin/bash
echo "This script will allow you to enter Groups and Users needed for new builds"
echo
echo
echo
echo

# Setting Variables for Group Section
Group=`cat /etc/group |grep "$group"`

echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: "  # Request User input to obtain group name
read group
echo "Searching /etc/group to see if the group "$group" exists."  # Checking to see if the group exists

if [ "$group" != "$Group" ]; then
        echo "The group already exist. Nothing more to do buddy."
else
        echo "We gotta add this one fella..carry on."

If you're on Linux, and thus have getent available:

printf "Group to search for: "
read -r group
if getent group "$group" >/dev/null 2>&1; then
  echo "$group exists"
else
  echo "$group does not exist"
fi

Using getent uses the standard C library for directory lookups. Thus, it's good for not only /etc/passwd , /etc/group , etc., but also directory services such as Active Directory, LDAP, NIS, YP and the like.

Here's what you do:

  1. Search for a group name
  2. Input the group name to search for

Sadly, you can't search for the group name before you input it, as this would violate causality and the laws of spacetime as we know them. Try searching after you know what you search for instead:

echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: "  # Request User input to obtain group name
read group

if cat /etc/group | grep -q "^$group:"
then 
    echo "The group already exist. Nothing more to do buddy."
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