Create A User in Ubuntu that Runs a Script and Logs Out [4 Steps]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Let’s say you are a system administrator. You want to create a special user where the user has only one task. He will log into your system, run a script and log out. However, the user may require to execute the script manually or automatically. In this article, I will explain all the necessary steps to create a user in Ubuntu that runs a script and logs out in a simple and comprehensible way.

Process Flow Chart Create A User in Ubuntu that Runs a Script and Logs Out:flow chart of the whole process

Distro Used Throughout the Tutorial: Ubuntu 22.04.1 LTS

Watch 4 Steps to Create a User in Ubuntu That Runs a Script and Logs Out

4 Steps to Create a User in Ubuntu That Runs a Script and Logs Out

In this section, I will explain the whole process to create a user in Ubuntu that runs a script and logs out. There can be different methods to complete a step. Here, I have provided the most convenient approach. However, you can configure your Ubuntu in two ways, one for a manual script running and the other for an automated script running.

You can read the Comparative Analysis of Methods section to configure your Ubuntu based on your requirements.

Step 1: Create User

You can easily create a new user in Ubuntu using the adduser command. This command prompts for password and other necessary information. In addition, to know more about creating users from the terminal, follow this article. Also, to create a user using the GUI, you can follow this article. I will create a user by the name of “script_runner” here. Follow the steps:

Note: The USER_NAME must not contain capital letters or special characters.

  1. At first, open a Terminal in Ubuntu.

  2. Copy the following command in the Terminal and press ENTER:

    sudo adduser script_runner
    EXPLANATION
    • sudo: Grants administrative privileges.
    • adduser: Adds a new user.
    • script_runner: Username of the new user.
  3. Give your password.

  4. Set a password for the newly created user.

  5. Provide other information or keep pressing ENTER to skip.

  6. At last, press Y to confirm your information.

Create a user in Ubuntu from Terminal that runs a script and logs out

Now, you can follow this process to verify the newly created user.

Step 2: Writing Script

In this section, I will create a folder named “myfolder” in the root directory (“/”) so that both the “walid” and “script_runner” can access the folder. Then I will place a script by the name of “myscript.sh” in that folder. Moreover, I have provided the script which you can download from the “Download” button. Now, do the following:

  1. Press CTRL+ALT+T to open a Terminal in Ubuntu.
  2. Insert the following command to create “myfolder” and press ENTER:
    sudo mkdir /myfolder
    EXPLANATION
    • sudo: Grants administrative privileges.
    • mkdir: Creates a Directory.
    • /: Root directory.
    • myfolder: name of the new directory.
  3. Now, give your password if necessary and hit ENTER again.Creating a directory named "myfolder"This will create a directory named “myfolder” in the home directory.
  4. Write the following command in the Terminal:
    sudo nano /myfolder/myscript.sh
    EXPLANATION
    • sudo: Grants elevated privileges.
    • nano: Opens a file in the nano text editor.
    • myscript: Name of my script.
    Opening myscript.sh in nano text editorThis will create a file named “myscript.sh” and open it in the nano text editor.
  5. Copy the following codes in the Terminal:
    #!/bin/bash
    
    echo “The script is executed at $(date)” >> /myfolder/myscript.sh
    
    if [[ ${0:0:1} == "-" ]]; then
        logout
    else
        exit
    fi
    
    EXPLANATION
    • echo: Displays a given text.
    • >>: Appends the output of a command in a file.
    • date: Shows current date and time.
    • if [[condition]]; then else fi: Checks a condition. If the condition is true, execute the command/commands after “then”. Otherwise, execute the command after “else”. ${0:0:1} == “-“: Checks if the first character of “$(0)” variable is “-” which denotes the shell in a login shell.
    • logout: Terminates a login shell.
    • exit: Terminates a non-login shell.
    Writing bash script for "ubuntu create a user that runs a script and logs out"

    If you try to use only the “logout” command in your script, you will get this error. Because the logout command is used to log out from a login shell. A login shell is a shell session and it starts when a user logs into a system. For a non-login shell, the exit command is required to log out. The value is “${0}” is “-bash” and “bash” for login and non-login shell respectively. That’s why I only used the first character to differentiate between login or non-login shell. Moreover, I used the date command to save execution time so that I can verify whether my script is really working or not.
  6. At last, press CTRL+O and ENTER to save.

Step 3: Configure Ubuntu

In this part, I have configured my Ubuntu. I want to run my script in two ways – manually and automatically.

A. Manual Execution

For a recap, I have created myfolder and myscript using sudo privileges. Now I will give script_runner ownership of the myfolder and myscript as a group with reading(r), writing(w) and executing(x) permissions. Check the steps:

  1. Launch a Ubuntu Terminal.
  2. Execute the following command one by one:
    sudo chown :script_runner /myfolder
    
    sudo chmod g+rwx /myfolder
    
    sudo chown :script_runner /myfolder/myscript.sh
    
    sudo chmod g+rwx /myfolder/myscript.sh
    EXPLANATION
    • sudo: Provides administrative privileges.
    • chown: Changes ownership.
    • chmod: Changes permission.
    • :script_runner: Giving script_runner ownership as a group.
    • g+rwx: Adding reading, writing and execution permissions to the group.
    • /myfolder: Path of the myfolder directory.
    • /myfolder/myscript.sh: Path of the myscript.sh file.

Changing ownership and permissions for "ubuntu create a user that runs a script and logs out"

You can check ownership and permissions following this section.


B. Automatic Execution

If you want the script to start running automatically when the script_runner logs in, you need to edit the .bashrc file of that user. To do so, follow the steps:

  1. Go to your Ubuntu and open a Terminal.
  2. Follow step 2 of Manual Execution.
  3. Write the following command to switch to the new user and hit ENTER:
    su - script_runner
    EXPLANATION
    • su: Switches to another user.
    • script_runner: Name of the target user.
  4. Provide the password for target user and press ENTER again.
  5. Copy the following command to open the .bashrc file:
    nano .bashrc
    EXPLANATION
    • nano: Opens a file in the nano text editor.
    • .bashrc: File that sets environmental variables.
  6. Now find the ENTER key on your keyboard and hit it.Switching to script_runner user and opening .bashrc file
  7. Add the following line at the end of the .bashrc file:
    source /myfolder/myscript.sh
  8. Finally, press CTRL +O and ENTER to save; press CTRL+X to exit.

Editing .bashrc for automation for "ubuntu create a user that runs a script and logs out"

Step 4: Verification

In this section, I will check whether my script is running properly or not.

A. Manual Execution of the Script

Firstly, I will switch to script_runner user and run the script manually:

  1. At first, launch an Ubuntu Terminal.
  2. Write the following command to switch to another user and press ENTER:
    su - script_runner
  3. Give password for target user and hit ENTER again.Switching to script_runner userIt is showing “script_runner@Ubuntu” instead of “walid@Ubuntu”.
  4. Copy the following command to change to myfolder directory and hit ENTER:
    cd /myfolder
  5. Now insert the following command to run the myscript.sh:
    source ./myscript.sh
    EXPLANATION
    • source: Reads and executes commands from a file in the current shell.
    • ./:  Denotes current directory.
  6. Press ENTER from your keyboard.sourcing myscript.shAs you can see I have been logged out and it is showing “walid@Ubuntu” again.
  7. Again, switch to script_runner by using the following command and provide the password:
    su - script_runner
  8. Finally, type the following command in the command prompt:
    cat /myfolder/myscript.log
    EXPLANATION
    • cat: Shows the contents of a file.
    • /myfolder/myscript.log: Path of the myscript.log file.

    Comparing execution time and current timeMy current date and time are February 27 and 11:55 AM which is quite similar to the time the log is showing. Evidently, myscript.sh has executed the commands and logged me out at the end.

B. Automatic Execution of the Script

This time the script will run automatically when I log in as script_runner and I will be logged out immediately:

  1. Go to your Ubuntu and press CTRL+ALT+T to open a Terminal.
  2. Insert the following command to switch user and hit ENTER:
    su - script_runner
  3. Provide password of the user and press ENTER again.
  4. Now copy the following command to view the myscript.log file:
    sudo cat /myfolder/myscript.log
    EXPLANATION
    • sudo: Grants root privileges.
    • cat: shows contents of a file.
  5. Finally, hit the ENTER button on your keyboard.Viewing the myscript.log file to verify "ubuntu create a user that runs a script and logs out"Again, you can see my current time and the execution time are quite similar. Which indicates everything is working just fine!



Comparative Analysis of Methods to Create A User in Ubuntu that Runs a Script and Logs Out

This section will help to decide whether you should go for manual execution or automatic execution of the script.

Methods Pros Cons
Manual Script Running
  • User has full control. He can edit the script, and decide whether he should run the script or not.
  • It saves time.
  • User needs to type commands on the Terminal to execute the script.
  • Room for human errors.
Automated Script

Running

  • The user doesn’t need to do anything except login.
  • Saves time.
  • The script cannot be modified in real-time.
  • No way to handle execution errors.

Finally, it’s up to you to decide which method suits better for your specific needs and requirements. You should weigh the pros and cons of each approach carefully. Personally, I prefer the automated method as it is more convenient.

How to Automatically Run Commands on SSH Login?

Sometimes, you may need to log into a remote server. Here, I will use the ssh command and Windows Powershell for that purpose. Now, follow the steps:

  1. Launch Windows Powershell.
  2. Write the following command in the Powershell and hit ENTER:
    ssh [email protected]
    EXPLANATION
    • ssh: Enables a secure connection using SSH protocol.
    • script_runner: Name of the user.
    • 192.168.235.129: IP address of the SSH server.
  3. Give the password of the user and hit ENTER again.Accessing server using SSH to verify "ubuntu create a user that runs a script and logs out"It is showing “Welcome to Ubuntu” at first and then the connection is closed. What happened here is first I logged into the server, then the script is executed and logged me out.

  4. Now Launch a Terminal in Ubuntu.
  5. Copy the following command to view the myscript.log file:
    sudo cat /myfolder/myscript.log
  6. Finally, press the ENTER button on your keyboard.Printing myscript.log fileAs you can see, there is another line in the myscript.log file that indicates the script is doing what it is supposed to do.

Check If the Newly Created User Exists in Ubuntu

Here I will show you how to check whether the newly created user is in the system or not. Now do the following to check user “script_runner”:

  1. Launch an Ubuntu Terminal.
  2. Write the following command in the command prompt:
    etent passwd | grep script_runner
    EXPLANATION
    • getent: Looks into the administrative database.
    • passwd: Contains user information.
    • pipe (|): Redirects output of a command to another command.
    • grep: Looks for a specific pattern.
    • script_runner: Username of the newly created user.
  3. Lastly, hit the ENTER button on your keyboard.Checking whether script_runner user exists or notIf you see the name of the newly created user in the output, that means the user has been created successfully.

log in as a root user using su - command



How to Check the Permission of Directories and Files in Linux?

To check the permission of the “myfolder” directory and its contents, follow the steps below:

  1. Firstly, press CTRL+ALT +T to open a Terminal in Ubuntu.
  2. Copy the following command in the Terminal and hit ENTER:
    ls -ld /myfolder
    EXPLANATION
    • ls: Lists files and directories.
    • -l: Shows detailed information.
    • -d: Shows only information of a directory, not its contents.
  3. Write the following command in the command prompt:
    ls -l /myfolder
  4. Lastly, find the ENTER button on your keyboard and press it.Checking ownership and permisssionsAs you can, the image above is showing ownership and the permissions of “myfolder”, “myscript.sh” and “myscript.log”.

How to Stop Automated Script Running in Linux?

To turn off auto script running after logging, you are required to edit the .bashrc file of that user and you need root privileges for that purpose. Now, to access the .bashrc file as a superuser, do the following:

  1. First, launch a Terminal in Ubuntu.
  2. Copy the following command to switch to superuser and hit ENTER:
    sudo su
    EXPLANATION
    • sudo: Grants elevated privileges.
    • su: Allows switching to another user.
    • sudo su: Combines both sudo and su command and switches to root user.
  3. Give your password and press ENTER again.
  4. Now insert the following command to access the .bashrc file:
    nano /home/script_runner/.bashrc
    EXPLANATION
    • nano: Opens file in Nano text editor.
    • /home/script_runner/.bashrc: Path of the .bashrc file of script_runner user.
  5. At last press the ENTER key from your keyboard.

Switching to root user and access .bashrc file for "ubuntu create a user that runs a script and logs out"

Common Challenges That May Arise to Create A User in Ubuntu that Runs a Script and Logs Out

While following the steps you may run into some issues. Here, I have mentioned some of the issues I faced with the explanation.

Not Login Shell: Use Exit

You will get this error when you use the “logout” command in your bash script.error message "not login shell"The logout command is only used to log out from a login shell. For a non-login shell, you need to use the “exit” command. The best approach is to combine both as I did in my script.

log in as a root user using su - command



Only Root May Add A User Or Group to the System

This is a command mistake that can happen to any user.error while creating new userRemember, to add a user you need to have sudo privileges and need to add the “sudo” command at the beginning like below:

sudo adduser script_runner

In addition, To know more about sudo, follow this article.

Permission Denied When Creating a Directory

If you  want to create a directory or file in the root directory (“/”), you might get this “Permission denied” message.Permission denied while creating directory in root directoryUse sudo at the beginning of your command like below:

sudo mkdir /myfolder

Conclusion

To complete the process described in this article, you will require prior knowledge of some concepts like bash scripting, sudo privileges etc. In this article, I have tried to explain every step in detail. By following those steps, you will be able to create a user in Ubuntu that runs a script and logs out.

People Also Ask

What is a superuser in Linux?

A superuser is a special type of user who enjoys administrative privileges. Linux can have multiple superuser accounts.

Are sudo and superuser similar?

No, they are not similar. Sudo is a command that allows a user to grant elevated privileges. Whereas, a superuser is a user who has elevated privileges.

How to run a bash script without executing permission?

You can use the bash command for this purpose. However, you need to provide the path of the script followed by the bash command like below:

bash /myfolder/myscript.sh

What does execution permission mean?

Execution permission means different things for different entities. If it’s a program or file, execution permission will allow a user to run the program or file. However, for a directory, it denotes a user will be able to enter into that directory and access the files.

How to give a user access to a file or folder?

To provide user access to a file or directory, you need to use the chown command. Let’s say I have a user named “dwight” and I want to give him ownership of a file named myoffice.txt, the command will be the following:

sudo chown dwight myoffice.txt

How to run a bash script as a root user?

To run a bash script as a root user, you will require to use sudo following by bash and the script’s path like below:

sudo bash /myscript.sh

What is the purpose of shebang (#!) in Linux?

It is a character sequence that tells a script which interpreter to use. For instance, “#!/bin/python3” means the script will use Python to run. But if the script isn’t written in Python language, you will see an error.

What does sourcing a script mean in Linux?

If you source a script, it will read the commands from the script and run it in the current shell. However, if you don’t source a script, your system will create a new process to run the script and it won’t affect your current shell.

What is a login shell?

A login shell is a type of shell. It starts when a user logs into a system and initializes the system environment and variables. The login shell also reads configuration files like .bashrc, .bash_profile etc.

What is the difference between the logout command and exit command?

The logout command and exit command are quite similar. However, the logout command is used to log out from a login shell. Whereas the exit command is used to terminate a non-login shell.


Relaed Articles

5/5 - (11 votes)
Walid Al Asad

Hello Everyone! I am Walid Al Asad. Currently, I am working at a tech company named Softeko as a Linux Content Developer Executive. I live in Dhaka, Bangladesh. I have completed my BSc. in Mechanical Engineering from Bangladesh University of Engineering and Technology (BUET). You can find me on LinkedIn, and ResearchGate. Read Full Bio

Leave a Comment