Manualmsdos
Manualmsdos

Reputation: 1545

How to enter sudo password if there are several commands on the same line in bash console

I wanted to run my Python script and then turn off my computer completely. After a while, I saw a screen on which sudo asked me for a password, which means that My computer was turned on for a few days just like that. I tried this, but it not worked:

sudo ls
python3 test.py && sudo shutdown now

So how can I run sudo with a password in one command line? Thanks for any help.

Upvotes: 1

Views: 623

Answers (4)

Mikhail
Mikhail

Reputation: 799

You can use:

$echo <password> | sudo -S <command>

and then clear bash history:

cat /dev/null > ~/.bash_history

Upvotes: 1

Aseider
Aseider

Reputation: 5925

You could reverse it and execute the script explicitly as your normal user

sudo sh -c 'sudo -u $SUDO_USER test.py && shutdown now'

Upvotes: 3

Manualmsdos
Manualmsdos

Reputation: 1545

I found solution here: https://superuser.com/a/67766

$echo <password> | sudo -S <command>

Just use pipe and -S key, for me looks like:

python3 test.py && echo <password> | sudo -S shutdown now

Upvotes: 1

tripleee
tripleee

Reputation: 189377

sudo can be configured to cache your password; but the simple and robust solution is to sudo the entire command line.

sudo sh -c ' ls; 
    python3 test.py && shutdown now'

Notice that this will run python3 as root, too, though. Generally you want to minimize the privileges for each command. If you have the privileges, of course, you could use su to run Python as your regular user from the privileged context.

Upvotes: 2

Related Questions