How to Switch User in Linux Shell Script

How to Switch User in Linux Shell Script

As Linux administrators, user switching is a common task, Switch User in Linux Shell Script, especially when performing tasks specific to different user roles. Similarly, as Oracle Database Administrators (DBAs), switching users becomes crucial for executing essential activities such as shutting down applications, in our upcoming blog post, we’ll illustrate how to effectively switch between users and execute commands, focusing on the ‘id’ command and saving its output.

Switch User in Linux Shell Script Objective

switch the user and execute the id command ‘su’

Prerequisites

  • Basic knowledge of bash script
  • Access the UNIX-based system eg LINUX
  • user existence eg like  ‘apps’
  • user password 

Notes

  • Please change the username and password according to your requirements.
  • Update the file path and enter the file name
  • Understand each command before executing the script to ensure it fits your environment and requirements.

Switch User in Linux Shell Script make sure your script has an executable permission 

chmod +x your_script_name.sh

once you have given the executable permission run the script 

./your_script_name.sh

Example output

script output

file output

Script 

#!/bin/bash
############################################################
# Date: 31-may-2024
# Author: Krishna Tummeti
# Website: Tech Base Hub
# Purpose: Switch the user and execute the id command
############################################################

# Switch to 'apps' user, and execute the id command.
echo "Switching to 'apps' user..."
echo "654321" | su - apps -c '
echo "This is the apps user-id"
id
exit
' > /tmp/id_output.txt

# Move the file from /tmp to /home/oracle/krishna and set permissions
sudo mv /tmp/id_output.txt /home/oracle/krishna/id_output.txt
sudo chown oracle:oracle /home/oracle/krishna/id_output.txt

# Execute the id command as Oracle user and append the output to the same file
echo ""
echo "Running id command as Oracle user..."
echo "This is the Oracle user-id" >> /home/oracle/krishna/id_output.txt
id >> /home/oracle/krishna/id_output.txt

# Execute the id command as root user and append the output to the same file
echo "Running id command as root user..."
echo "This is the root user id" >> /home/oracle/krishna/id_output.txt
sudo id >> /home/oracle/krishna/id_output.txt

# Verify the file.

echo "Verifying file updated by root user..."
if [[ -f /home/oracle/krishna/id_output.txt ]]; then
echo 'File updated by the root user.'
else
echo 'File not updated by the root user.'
fi

echo "Script completed."

Thank You

Leave a Comment