0
0
Linux CLIscripting~15 mins

su (switch user) in Linux CLI - Mini Project: Build & Apply

Choose your learning style9 modes available
Switch User with su Command
📖 Scenario: You are managing a Linux system where you need to switch between users to perform different tasks. Using the su command helps you switch to another user account temporarily.
🎯 Goal: Learn how to use the su command to switch users, set a target user variable, and verify the current user after switching.
📋 What You'll Learn
Create a variable holding the target username
Use the su command with the target username
Check the current user after switching
Print the current user to confirm the switch
💡 Why This Matters
🌍 Real World
System administrators often need to switch users to perform tasks with different permissions. Automating this with scripts saves time and reduces errors.
💼 Career
Knowing how to use the su command and automate user switching is useful for Linux system administrators, DevOps engineers, and anyone managing multi-user systems.
Progress0 / 4 steps
1
Set the target user variable
Create a variable called target_user and set it to the exact string guest.
Linux CLI
Need a hint?

Use target_user = 'guest' to store the username.

2
Switch user using su command
Write a command string called switch_command that uses su with the -c option to run whoami as the user stored in target_user. Use double quotes and f-string style formatting exactly as switch_command = f"su {target_user} -c 'whoami'".
Linux CLI
Need a hint?

Use f"su {target_user} -c 'whoami'" to build the command string.

3
Execute the switch command and capture output
Use the subprocess module to run the command stored in switch_command. Import subprocess and use subprocess.run with shell=True, capture the output, decode it to a string, and store it in a variable called current_user. Use current_user = subprocess.run(switch_command, shell=True, capture_output=True).stdout.decode().strip() exactly.
Linux CLI
Need a hint?

Use import subprocess and subprocess.run(...).stdout.decode().strip() to get the output.

4
Print the current user
Write a print statement to display the value of current_user exactly as print(current_user).
Linux CLI
Need a hint?

Use print(current_user) to show the switched user.