简体   繁体   中英

Bash scripting check if multiple groups exists

I need to add an user to multiple supplementary groups by using the command

usermod -aG group1,group2 username

Need help for the error checking for the script to search if the multiple groups exists in the /etc/group file. This is what i have.

read -p "Enter groups" groups
if (Check if those groups exists)
then
  usermod -aG "$groups $username
else
  echo "Group(s) does not exists"
fi

Please help thanks! Sorry im a newbie if possible let me know some links to read.

Alright I came out with something which actually worked. Will appreciate if it could be "cleaned" by someone. XD

    read -p "Enter user" user
    read -p "Enter groups" groups
    storegroups=$(echo $groups | awk -F, '{print $1" "$2" "$3}')
    if [ "$(getent group $storegroups | wc -l)" == $(echo $storegroups | wc -w)" ]
    then 
        usermod -ag $groups $user
    else
        echo "1 or more groups does not exists"
    fi
#!/bin/bash

read -p "Enter username: " username
read -p "Enter groups: " groups

for g in ${groups//,/ }; do
  grep -q "^$g:" /etc/group
  ret=$?                         # save returncode of grep
  if [[ $ret -eq 0 ]]; then
    usermod -aG "$g" "$username"
  else
    echo "Group $g does not exists"
  fi
done
read -p "Enter user: " user
read -p "Enter groups: " groups

# Replace , with space
groupswithSpace=$(echo $groups | tr ',' ' ')

#getent returns 0 only if all groups are valid
getent group $groupswithSpace > /dev/null

if [ $? -eq 0 ]
then
    usermod -ag $groups $user
else
    echo "1 or more groups does not exists"
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