1

I am writing a bash script to install some small software I'm developing. That script is run with sudo (as root), but some of the commands that are executed by the script need (or should be) run with a regular user whose name I keep in the $userName variable. Most of the commands are one liners and su -c "/what/ever/command" $userName works good enough.

However, one of those commands I don't want to run as root is going to ask me things (actually, only one thing, but many times: whether it should overwrite an existing file or not). That command which I may call "baaad_command" doesn't have any option to provide a default answer (there's no "--assume-no" or anything like that).

The only option I see feasible is using the expect command, and reply "n\r" every time the command outputs and string witch starts with "Overwrite", I want my script to reply no (meaning "n\r") as many times as baaad_command asks "Overwrite... ? [y/n]"

I've tried many different combinations of su, spawn, expect... without any luck.

This is my last try so far:

#!/bin/bash
if [[ -d "$destinationFolder" ]] ; then
    if [[ -n "$userName" ]] ; then
        spawned=$(su -c expect -c "
            spawn baaad_command --user \"foo\" --passwd \"bar\" \"$destinationFolder\"
             expect {
                 Overwrite: { send \"n\r\"; exp_continue }
                 eof { exit }
             }
        " )
    else
        echo "Don't have a non-root username to install baaad_command with. Skipping"
        exit 3
    fi
else
        echo "$destinationFolder directory not found in $(pwd). Can't continue"
        exit 2
fi

It doesn't have any remarkable thing over the other 200 tries... just happens to be the last.

Any hint will be very appreciated. Thank you in advance.

  • you can try to send the answer via pipe. smth like yes n|baaad_command in some cases may work. – rush Mar 22 '12 at 20:54
7

You probably need to use su -c 'expect -c "spawn ..."' -- note the extra quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.