-1

I am logged in as root than I am running a script with below contents

#! /bin/bash
id studentapp if [ $? -eq 0 ]; 
then  echo " SKIPPING user creation" 
else useradd studentapp 
echo " User created" 
fi 
cd /home/studentapp

Any idea...

Sobhit Sharma
  • 697
  • 14
  • 45
stalin
  • 369
  • 2
  • 5

1 Answers1

1

Maybe you needs su studentapp in else block if user was created. cd changes working directory. If user was not created - maybe there are no such directory.

su man page

cd man page

Also it's can be helpful for you:

check if user exists

check if direcory exists

Update

#! /bin/bash
id studentapp
if [ $? -eq 0 ];
then
    echo "user exists" 
else
    useradd studentapp --create-home
    passwd studentapp
    echo "user created" 
fi
su studentapp
cd /home/studentapp
yaroslavche
  • 383
  • 1
  • 9
  • if I go to the consol i can find the user and can switch manually but not via script please find the consol snapshot [root@instance-1 sunnyisgone]# cd /home/studentapp [root@instance-1 studentapp]# – stalin Oct 14 '18 at 15:39
  • try this: #! /bin/bash
    id studentapp if [ $? -eq 0 ]; then echo "user exists" else useradd studentapp echo "user created" su studentapp fi cd /home/studentapp ```
    – yaroslavche Oct 14 '18 at 15:48
  • still same issue. I am using centos vm on google cloud. May be I will try on actuall machine can will get back to you. – stalin Oct 14 '18 at 15:55
  • `useradd` command creates a locked user account. You need also unlock the account by issuing the `passwd` command to assign a password. – yaroslavche Oct 14 '18 at 16:08
  • the code you gave earlier worked. Thanks. Actually Su studentapp command did the trick. thanks.may be "passwd studentapp" will be need as Ihave not tested the full stack but as of now its working. – stalin Oct 14 '18 at 16:13
  • You're welcome =) Also current user home dir stored in `$HOME` variable. So you can change dir with `cd $HOME` or `cd ~` – yaroslavche Oct 14 '18 at 16:24