Shell script: Determine whether users and user groups already exist/create users and user groups

Source: Internet
Author: User
Tags egrep

Typically, as a deployment script for an application, the first task that begins is to create a dedicated (dedicated) user and user group for the current app. This script is very simple, a reference sample is attached here:

[Plain]View Plaincopy
    1. #!/bin/sh
    2. User=test_user
    3. Group=test_group
    4. #create group if not exists
    5. Egrep "^ $group"/etc/group >&/dev/null
    6. If [$?-ne 0]
    7. Then
    8. Groupadd $group
    9. Fi
    10. #create user if not exists
    11. Egrep "^ $user"/etc/passwd >&/dev/null
    12. If [$?-ne 0]
    13. Then
    14. Useradd-g $group $user
    15. Fi

For adding users, we can also use the ID command to determine whether a user exists, so that the creation of a user's script can be written like this:

[Plain]View Plaincopy
    1. #create user if not exists
    2. ID $user >&/dev/null
    3. If [$?-ne 0]
    4. Then
    5. Useradd-g $group $user
    6. Fi

However, using the ID command does not tell if a user group already exists! As for the use of id-g $user can only give an existing user to belong to the user group is what, and can not tell whether a user group is already exist, so, in order to use the script to handle the unified, we use unified from/etc/group and/etc/ passwd file to find out the way to determine whether a user group and users exist!

Shell script: Determine whether users and user groups already exist/create users and user groups

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.