I try to use vi commands in a script, in addition I try to pass sudo password in same script. So I have something like:
echo mypassword | bash -c "echo $'Goappendthis\E:x\n' | sudo vi /etc/test"
vi command is successful but it still keeps asking password. How I can do it w/o password so I can run same command for multiple hosts in a script?
First: Don't do this. Use a privilege escalation mechanism that doesn't require passwords to be passed around.
Second: Unless given -S
or --stdin
, sudo
reads passwords directly from the TTY, not from stdin.
Third: You need to direct the password to sudo
's stdin without also overriding vi
's stdin. Doing that might look like the following:
echo mypassword | sudo --stdin -- bash -c "echo $'Goappendthis\E:x\n' | vi /etc/test"