简体   繁体   中英

Run sudo command in shell script

I wrote a shell script like this

#!/bin/bash

sudo mkdir /var/www/html/test
sudo cp ./index.html /var/www/html/test/index.html
echo "Hi" > /var/www/html/test/index.html

if I runt this with sudo it works well.

$ sudo ./script.sh

but I don't want to run with sudo . because echo doesn't need root privilege. In other hand if I run this without sudo like this:

$ ./script.sh

for the first command ( mkdir ) it asks me for root password and second command doesn't run and give me a permission denied error.

How can I handle this situation?

Based on your setup, eg in ubuntu if I run sudo 2 times, the second time I don't have to give the password. So it is possible that the second sudo DID run, without asking for password again.

You can clarify, try this:

sudo echo a
sudo echo b

It is most likely, as Kip K commented, the error originates from the echo "Hi"... since the normal user has no permission to write /var/www/html/test/index.html .

Kinda overkill, but you can give constant feedback like this:

sudo bash -c 'echo mkdir; mkdir /var/www/html/test'
sudo bash -c 'echo cp; cp ./index.html /var/www/html/test/index.html'

Try chown for directory test :

#!/bin/bash

sudo bash -c 'mkdir /var/www/html/test && chown -R USER /var/www/html/test'
cp ./index.html /var/www/html/test/index.html
echo "Hi" > /var/www/html/test/index.html

or ... chmod o+w /var/www/html/test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM