Skip to content

Instantly share code, notes, and snippets.

@hayakawa
Created June 6, 2014 12:57
Show Gist options
  • Save hayakawa/ddccad852d3493eff34e to your computer and use it in GitHub Desktop.
Save hayakawa/ddccad852d3493eff34e to your computer and use it in GitHub Desktop.
usrgrp_add.sh
#!/bin/bash
# Pre-check
if [ -f ./group.list ];
then
echo "[SUCCESS] ./group.list is found"
else
echo "[ERROR] ./group.list file is not found.";
exit 1;
fi
if [ -f ./user.list ];
then
echo "[SUCCESS] ./user.list is found"
else
echo "[ERROR] ./user.list file is not found.";
exit 1;
fi
# Load some files
ADD_GROUPS=( `cat ./group.list | tr -d '\r' | tr '\n' ' '` );
ADD_USERS=( `cat ./user.list | tr -d '\r' | tr '\n' ' '` );
# Add some Groups
for i in "${ADD_GROUPS[@]}"; do
# Get group id and group name.
GRPID=`echo ${i} | cut -f 1 -d:`;
GRPNM=`echo ${i} | cut -f 2 -d:`;
CHKID=`echo "${GRPID}" | sed "s/[a-zA-Z].*//g"`;
CHKNM=`echo "${GRPNM}" | sed "s/[0-9].*//g"`;
# Check group id and group name.
if [ -z ${GRPID} -o -z ${GRPNM} ];
then
echo "[ERROR] id or name is empty";
exit 1;
fi
if [ x"${GRPID}" != x"${CHKID}" ];
then
echo "[ERROR] Bad id(${GRPID})";
exit 1;
fi
if [ -z ${CHKNM} ];
then
echo "[ERROR] Bad name(${GRPNM})";
exit 1;
fi
if [ ${GRPID} = ${GRPNM} ];
then
echo "[ERROR] Bad id(ID=${GRPID}) or name(NAME=${GRPNM})";
exit 1;
fi
if [ x"`grep ${GRPNM} /etc/group`" = "x" ];
then
groupadd -g ${GRPID} ${GRPNM} >/dev/null 2>&1
if [ "$?" = "0" ];
then
echo "[SUCCESS] Group ${GRPNM}(GID=${GRPID}) is added.";
else
echo "[ERROR] Group ${GRPNM}(GID=${GRPID}) is not able to add.";
exit 1;
fi
else
echo "[SKIP] ${GRPNM} is already exists.";
fi
done
# Add some Users
for i in "${ADD_USERS[@]}"; do
# Get user id and user name.
USRID=`echo ${i} | cut -f 1 -d:`;
USRNM=`echo ${i} | cut -f 2 -d:`;
USRGR=`echo ${i} | cut -f 3 -d:`;
CHKID=`echo "${USRID}" | sed "s/[a-zA-Z].*//g"`;
CHKNM=`echo "${USRNM}" | sed "s/[0-9].*//g"`;
CHKGR=`echo "${USRGR}" | sed "s/[0-9].*//g"`;
# Check user id and user name.
if [ -z ${USRID} -o -z ${USRNM} ];
then
echo "[ERROR] id or name is empty";
exit 1;
fi
if [ x"${USRID}" != x"${CHKID}" ];
then
echo "[ERROR] Bad id(${USRID})";
exit 1;
fi
if [ -z ${CHKNM} ];
then
echo "[ERROR] Bad name(${USRNM})";
exit 1;
fi
if [ ${USRID} = ${USRNM} ];
then
echo "[ERROR] Bad id(ID=${USRID}) or name(NAME=${USRNM})";
exit 1;
fi
if [ -z ${CHKGR} ];
then
echo "[ERROR] Bad group(${USRGR})";
exit 1;
fi
if [ x"`grep ${USRNM} /etc/passwd`" = "x" ];
then
useradd -d /home/${USRNM} -m -s /bin/bash -u ${USRID} -g ${USRGR} ${USRNM} >/dev/null 2>&1
if [ "$?" = "0" ];
then
echo "[SUCCESS] User ${USRNM}(UID=${USRID}) is added.";
else
echo "[ERROR] User ${USRNM}(GID=${USRID}) is not able to add.";
exit 1;
fi
else
echo "[SKIP] ${USRNM} is already exists.";
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment