Trying to script with 'useradd', can't understand examples The Next CEO of Stack OverflowWhy is printf better than echo?Can't understand this script. bash <<(curl -s http://xxx.com)can I tell to useradd to execute a script? Maybe in /etc/default/useradd?Why useradd -m doesn't fill created home dir with some defaults?Can't add users anymore by using useraddCreating user with bash script with argumentsDefault shell not being selected with useraddSeeking a script that can loop ssh to a list of ips and perform useradd, home directory, creation and the user to the sudoers fileuseradd on CentOS with home directory and sudo privilegesuseradd with no optionsTrying to understand how to work with IFS

Does it take more energy to get to Venus or to Mars?

What is the purpose of the Evocation wizard's Potent Cantrip feature?

Putting a 2D region plot under a 3D plot

Text adventure game code

How can I quit an app using Terminal?

What is meant by a M next to a roman numeral?

Can a single photon have an energy density?

Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?

Unreliable Magic - Is it worth it?

If I blow insulation everywhere in my attic except the door trap, will heat escape through it?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

Should I tutor a student who I know has cheated on their homework?

How to use tikz in fbox?

Why is there a PLL in CPU?

Why does C# sound extremely flat when saxophone is tuned to G?

% symbol leads to superlong (forever?) compilations

How do spells that require an ability check vs. the caster's spell save DC work?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Customer Requests (Sometimes) Drive Me Bonkers!

Error when running sfdx update to 7.1.3 then sfdx push errors

Fastest way to shutdown Ubuntu Mate 18.10

Where to find order of arguments for default functions

What's the point of interval inversion?

Why here is plural "We went to the movies last night."



Trying to script with 'useradd', can't understand examples



The Next CEO of Stack OverflowWhy is printf better than echo?Can't understand this script. bash <<(curl -s http://xxx.com)can I tell to useradd to execute a script? Maybe in /etc/default/useradd?Why useradd -m doesn't fill created home dir with some defaults?Can't add users anymore by using useraddCreating user with bash script with argumentsDefault shell not being selected with useraddSeeking a script that can loop ssh to a list of ips and perform useradd, home directory, creation and the user to the sudoers fileuseradd on CentOS with home directory and sudo privilegesuseradd with no optionsTrying to understand how to work with IFS










0















I am trying to use useradd. I found an example of something I'd like to try and incorporate, though I can't understand specific parts.



Here is the example in entirety:



if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " username
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1


I understand the basics what is going on, but specifically:



[ $(id -u) -eq 0 ];


and



[ $? -eq 0 ];


I'm guessing a variable is being made within the brackets. But I've been stumped deciphering their purpose or meaning.










share|improve this question









New contributor




user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    0















    I am trying to use useradd. I found an example of something I'd like to try and incorporate, though I can't understand specific parts.



    Here is the example in entirety:



    if [ $(id -u) -eq 0 ]; then
    read -p "Enter username : " username
    read -s -p "Enter password : " password
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
    echo "$username exists!"
    exit 1


    I understand the basics what is going on, but specifically:



    [ $(id -u) -eq 0 ];


    and



    [ $? -eq 0 ];


    I'm guessing a variable is being made within the brackets. But I've been stumped deciphering their purpose or meaning.










    share|improve this question









    New contributor




    user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      0












      0








      0








      I am trying to use useradd. I found an example of something I'd like to try and incorporate, though I can't understand specific parts.



      Here is the example in entirety:



      if [ $(id -u) -eq 0 ]; then
      read -p "Enter username : " username
      read -s -p "Enter password : " password
      egrep "^$username" /etc/passwd >/dev/null
      if [ $? -eq 0 ]; then
      echo "$username exists!"
      exit 1


      I understand the basics what is going on, but specifically:



      [ $(id -u) -eq 0 ];


      and



      [ $? -eq 0 ];


      I'm guessing a variable is being made within the brackets. But I've been stumped deciphering their purpose or meaning.










      share|improve this question









      New contributor




      user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      I am trying to use useradd. I found an example of something I'd like to try and incorporate, though I can't understand specific parts.



      Here is the example in entirety:



      if [ $(id -u) -eq 0 ]; then
      read -p "Enter username : " username
      read -s -p "Enter password : " password
      egrep "^$username" /etc/passwd >/dev/null
      if [ $? -eq 0 ]; then
      echo "$username exists!"
      exit 1


      I understand the basics what is going on, but specifically:



      [ $(id -u) -eq 0 ];


      and



      [ $? -eq 0 ];


      I'm guessing a variable is being made within the brackets. But I've been stumped deciphering their purpose or meaning.







      shell-script useradd






      share|improve this question









      New contributor




      user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited yesterday









      Rui F Ribeiro

      41.8k1483142




      41.8k1483142






      New contributor




      user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked yesterday









      user7055355user7055355

      31




      31




      New contributor




      user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      user7055355 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          2 Answers
          2






          active

          oldest

          votes


















          0














          From man:




          -u, --user



           print only the effective user ID



          id -u will print the ID of the user. The script is restricted to root user which UID is 0.



          $? exit status of the previously executed command.






          share|improve this answer























          • OK! I get it, thanks. So in this case will $? looking for the exit status of egrep? Zero meaning egrep matched a user, triggering '$username exists!`?

            – user7055355
            yesterday











          • @user7055355 exit status 0 means egrep execution is success.

            – msp9011
            yesterday


















          0














          The id utility, when used with its -u option, will output the UID of the current user. If that UID is zero, then the user is the root user. Only the root user should add new users.



          Therefore, the script tests the UID of the user running the script agains zero and only performs the privileged actions (not shown in the script in the question) if the user is root.



          An arguably better way to handle this in the script, if the whole script requires root, is to check whether the UID is non-zero at the start and exit with an error if it is:



          if [ "$(id -u)" -ne 0 ]; then
          echo 'You are not root. Try again with sudo.' >&2
          exit 1
          fi


          As for the $?, it's a special shell variable that always contains the exit status of the most recently executed command. It is very rare to need to use this directly, as if is more than capable of working directly with grep:



          if grep -q "^$username" /etc/passwd; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Here, if will use the exit status of grep. We use grep with -q to stop it from producing any output and from parsing the whole file past any first match. It just returns an exit status that if will use. We also don't need egrep as the regular expression is not an extended regular expression (egrep is identical to grep -E).



          Note also that diagnostic messages should be written to the standard error stream. You may do this by redirecting your messages with >&2. Also, printf is preferred over echo when outputting variable data.



          If you are on a system where a directory service such as NIS or LDAP is used, grepping for an existing user in /etc/passwd may not be useful as the actual users may well be stored in a separate database.



          On such systems, it may be better to use getent passwd "$username" (this would work on non-NIS/LDAP systems too). This would return the password database entry for the particular user, or exit with a non-zero exit status, which means we could use that in our test:



          if getent passwd "$username" >/dev/null; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Just note that useradd can't add users to a NIS or LDAP database...



          Although, strictly speaking nothing of the above should really be needed as useradd should not do anything useful if the current user is not root or if the user being added already exists.






          share|improve this answer

























          • Very, very helpful, thank you! I can see all the redundancies now.

            – user7055355
            yesterday











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "106"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          user7055355 is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f508892%2ftrying-to-script-with-useradd-cant-understand-examples%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          From man:




          -u, --user



           print only the effective user ID



          id -u will print the ID of the user. The script is restricted to root user which UID is 0.



          $? exit status of the previously executed command.






          share|improve this answer























          • OK! I get it, thanks. So in this case will $? looking for the exit status of egrep? Zero meaning egrep matched a user, triggering '$username exists!`?

            – user7055355
            yesterday











          • @user7055355 exit status 0 means egrep execution is success.

            – msp9011
            yesterday















          0














          From man:




          -u, --user



           print only the effective user ID



          id -u will print the ID of the user. The script is restricted to root user which UID is 0.



          $? exit status of the previously executed command.






          share|improve this answer























          • OK! I get it, thanks. So in this case will $? looking for the exit status of egrep? Zero meaning egrep matched a user, triggering '$username exists!`?

            – user7055355
            yesterday











          • @user7055355 exit status 0 means egrep execution is success.

            – msp9011
            yesterday













          0












          0








          0







          From man:




          -u, --user



           print only the effective user ID



          id -u will print the ID of the user. The script is restricted to root user which UID is 0.



          $? exit status of the previously executed command.






          share|improve this answer













          From man:




          -u, --user



           print only the effective user ID



          id -u will print the ID of the user. The script is restricted to root user which UID is 0.



          $? exit status of the previously executed command.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          msp9011msp9011

          4,54244167




          4,54244167












          • OK! I get it, thanks. So in this case will $? looking for the exit status of egrep? Zero meaning egrep matched a user, triggering '$username exists!`?

            – user7055355
            yesterday











          • @user7055355 exit status 0 means egrep execution is success.

            – msp9011
            yesterday

















          • OK! I get it, thanks. So in this case will $? looking for the exit status of egrep? Zero meaning egrep matched a user, triggering '$username exists!`?

            – user7055355
            yesterday











          • @user7055355 exit status 0 means egrep execution is success.

            – msp9011
            yesterday
















          OK! I get it, thanks. So in this case will $? looking for the exit status of egrep? Zero meaning egrep matched a user, triggering '$username exists!`?

          – user7055355
          yesterday





          OK! I get it, thanks. So in this case will $? looking for the exit status of egrep? Zero meaning egrep matched a user, triggering '$username exists!`?

          – user7055355
          yesterday













          @user7055355 exit status 0 means egrep execution is success.

          – msp9011
          yesterday





          @user7055355 exit status 0 means egrep execution is success.

          – msp9011
          yesterday













          0














          The id utility, when used with its -u option, will output the UID of the current user. If that UID is zero, then the user is the root user. Only the root user should add new users.



          Therefore, the script tests the UID of the user running the script agains zero and only performs the privileged actions (not shown in the script in the question) if the user is root.



          An arguably better way to handle this in the script, if the whole script requires root, is to check whether the UID is non-zero at the start and exit with an error if it is:



          if [ "$(id -u)" -ne 0 ]; then
          echo 'You are not root. Try again with sudo.' >&2
          exit 1
          fi


          As for the $?, it's a special shell variable that always contains the exit status of the most recently executed command. It is very rare to need to use this directly, as if is more than capable of working directly with grep:



          if grep -q "^$username" /etc/passwd; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Here, if will use the exit status of grep. We use grep with -q to stop it from producing any output and from parsing the whole file past any first match. It just returns an exit status that if will use. We also don't need egrep as the regular expression is not an extended regular expression (egrep is identical to grep -E).



          Note also that diagnostic messages should be written to the standard error stream. You may do this by redirecting your messages with >&2. Also, printf is preferred over echo when outputting variable data.



          If you are on a system where a directory service such as NIS or LDAP is used, grepping for an existing user in /etc/passwd may not be useful as the actual users may well be stored in a separate database.



          On such systems, it may be better to use getent passwd "$username" (this would work on non-NIS/LDAP systems too). This would return the password database entry for the particular user, or exit with a non-zero exit status, which means we could use that in our test:



          if getent passwd "$username" >/dev/null; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Just note that useradd can't add users to a NIS or LDAP database...



          Although, strictly speaking nothing of the above should really be needed as useradd should not do anything useful if the current user is not root or if the user being added already exists.






          share|improve this answer

























          • Very, very helpful, thank you! I can see all the redundancies now.

            – user7055355
            yesterday















          0














          The id utility, when used with its -u option, will output the UID of the current user. If that UID is zero, then the user is the root user. Only the root user should add new users.



          Therefore, the script tests the UID of the user running the script agains zero and only performs the privileged actions (not shown in the script in the question) if the user is root.



          An arguably better way to handle this in the script, if the whole script requires root, is to check whether the UID is non-zero at the start and exit with an error if it is:



          if [ "$(id -u)" -ne 0 ]; then
          echo 'You are not root. Try again with sudo.' >&2
          exit 1
          fi


          As for the $?, it's a special shell variable that always contains the exit status of the most recently executed command. It is very rare to need to use this directly, as if is more than capable of working directly with grep:



          if grep -q "^$username" /etc/passwd; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Here, if will use the exit status of grep. We use grep with -q to stop it from producing any output and from parsing the whole file past any first match. It just returns an exit status that if will use. We also don't need egrep as the regular expression is not an extended regular expression (egrep is identical to grep -E).



          Note also that diagnostic messages should be written to the standard error stream. You may do this by redirecting your messages with >&2. Also, printf is preferred over echo when outputting variable data.



          If you are on a system where a directory service such as NIS or LDAP is used, grepping for an existing user in /etc/passwd may not be useful as the actual users may well be stored in a separate database.



          On such systems, it may be better to use getent passwd "$username" (this would work on non-NIS/LDAP systems too). This would return the password database entry for the particular user, or exit with a non-zero exit status, which means we could use that in our test:



          if getent passwd "$username" >/dev/null; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Just note that useradd can't add users to a NIS or LDAP database...



          Although, strictly speaking nothing of the above should really be needed as useradd should not do anything useful if the current user is not root or if the user being added already exists.






          share|improve this answer

























          • Very, very helpful, thank you! I can see all the redundancies now.

            – user7055355
            yesterday













          0












          0








          0







          The id utility, when used with its -u option, will output the UID of the current user. If that UID is zero, then the user is the root user. Only the root user should add new users.



          Therefore, the script tests the UID of the user running the script agains zero and only performs the privileged actions (not shown in the script in the question) if the user is root.



          An arguably better way to handle this in the script, if the whole script requires root, is to check whether the UID is non-zero at the start and exit with an error if it is:



          if [ "$(id -u)" -ne 0 ]; then
          echo 'You are not root. Try again with sudo.' >&2
          exit 1
          fi


          As for the $?, it's a special shell variable that always contains the exit status of the most recently executed command. It is very rare to need to use this directly, as if is more than capable of working directly with grep:



          if grep -q "^$username" /etc/passwd; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Here, if will use the exit status of grep. We use grep with -q to stop it from producing any output and from parsing the whole file past any first match. It just returns an exit status that if will use. We also don't need egrep as the regular expression is not an extended regular expression (egrep is identical to grep -E).



          Note also that diagnostic messages should be written to the standard error stream. You may do this by redirecting your messages with >&2. Also, printf is preferred over echo when outputting variable data.



          If you are on a system where a directory service such as NIS or LDAP is used, grepping for an existing user in /etc/passwd may not be useful as the actual users may well be stored in a separate database.



          On such systems, it may be better to use getent passwd "$username" (this would work on non-NIS/LDAP systems too). This would return the password database entry for the particular user, or exit with a non-zero exit status, which means we could use that in our test:



          if getent passwd "$username" >/dev/null; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Just note that useradd can't add users to a NIS or LDAP database...



          Although, strictly speaking nothing of the above should really be needed as useradd should not do anything useful if the current user is not root or if the user being added already exists.






          share|improve this answer















          The id utility, when used with its -u option, will output the UID of the current user. If that UID is zero, then the user is the root user. Only the root user should add new users.



          Therefore, the script tests the UID of the user running the script agains zero and only performs the privileged actions (not shown in the script in the question) if the user is root.



          An arguably better way to handle this in the script, if the whole script requires root, is to check whether the UID is non-zero at the start and exit with an error if it is:



          if [ "$(id -u)" -ne 0 ]; then
          echo 'You are not root. Try again with sudo.' >&2
          exit 1
          fi


          As for the $?, it's a special shell variable that always contains the exit status of the most recently executed command. It is very rare to need to use this directly, as if is more than capable of working directly with grep:



          if grep -q "^$username" /etc/passwd; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Here, if will use the exit status of grep. We use grep with -q to stop it from producing any output and from parsing the whole file past any first match. It just returns an exit status that if will use. We also don't need egrep as the regular expression is not an extended regular expression (egrep is identical to grep -E).



          Note also that diagnostic messages should be written to the standard error stream. You may do this by redirecting your messages with >&2. Also, printf is preferred over echo when outputting variable data.



          If you are on a system where a directory service such as NIS or LDAP is used, grepping for an existing user in /etc/passwd may not be useful as the actual users may well be stored in a separate database.



          On such systems, it may be better to use getent passwd "$username" (this would work on non-NIS/LDAP systems too). This would return the password database entry for the particular user, or exit with a non-zero exit status, which means we could use that in our test:



          if getent passwd "$username" >/dev/null; then
          printf 'User "%s" already existsn' "$username" >&2
          exit 1
          fi


          Just note that useradd can't add users to a NIS or LDAP database...



          Although, strictly speaking nothing of the above should really be needed as useradd should not do anything useful if the current user is not root or if the user being added already exists.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered yesterday









          KusalanandaKusalananda

          138k17258426




          138k17258426












          • Very, very helpful, thank you! I can see all the redundancies now.

            – user7055355
            yesterday

















          • Very, very helpful, thank you! I can see all the redundancies now.

            – user7055355
            yesterday
















          Very, very helpful, thank you! I can see all the redundancies now.

          – user7055355
          yesterday





          Very, very helpful, thank you! I can see all the redundancies now.

          – user7055355
          yesterday










          user7055355 is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          user7055355 is a new contributor. Be nice, and check out our Code of Conduct.












          user7055355 is a new contributor. Be nice, and check out our Code of Conduct.











          user7055355 is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Unix & Linux Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f508892%2ftrying-to-script-with-useradd-cant-understand-examples%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

          Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

          Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.