Whenever I need to login as root in bash I use su command.
What if I need to login as root using a bash script?? After the command bash prompts for password.
What if I need to login as root using a bash script?? After the command bash prompts for password.
I tried to write a bash script for the same but could not. I did some googling again got no solution. Then I remembered about a shell utility Expect. I installed it and wrote some simple scripts.
spawn su expect "Password: " send "rootpassword\r" expect "#" interact
With this script we are left logged into the root and we can run any bash commands there after.
I wrote the next one by mixing bash and expect.#!/bin/bash /usr/bin/expect << EOD set timeout 120 spawn su expect "Password: " send "rootpassword\r" expect "#" EOD echo "\r" ls
But with this we are logged out (we can't interact in the shell as root) after completion of the script.

