5

I have a script (let's name it parent.sh) that calls some other scripts based on input parameters.

Finally, it calls the script child.sh.
child.sh requests user's input in case it find that some files already exists:

"Would you like to replace the configuration file with a new one? (Yes/No/Abort): "

Now, what I want to do it to simulate the keystroke of "Y"/"y" inside the parent.sh script in order to always overwrite the files.

I cannot use expect.

How can I do that?

6
  • 4
    How is child.sh getting the input? If simply reads from STDIN, then echo y | child.sh should do it. (If the question may occur multiple times, then yes y | child.sh.)
    – manatwork
    Feb 26, 2013 at 8:20
  • 1
    @manatwork that's really an answer. I was about to post it but that would then called a copy-paste. :)
    – mtk
    Feb 26, 2013 at 8:28
  • May be an answer, unless parent.sh already passes input to child.sh, so child.sh reads user input from /dev/tty.
    – manatwork
    Feb 26, 2013 at 8:32
  • parent.sh call child.sh as follows: ... bla bla ... child.sh option
    – Peter
    Feb 26, 2013 at 9:01
  • @Peter: man yes, read it
    – goldilocks
    Feb 26, 2013 at 9:17

1 Answer 1

1

While yes | child.sh as manatwork already commented is a valid solution, from a programmers point of view I would patch child.sh to be able to handle this usecase.

Like add an --force option to not prompt but always overwrite files.

But to answer the subject of your question and to get something more expect-like and not only fire y via a pipe:

#!/bin/bash

fifo=fifo

mkfifo ${fifo}

exec 3<> ${fifo}

expect="Would you like to replace the configuration file with a new one? (Yes/No/Abort): "
answer="y"

while IFS= read -d $'\0' -n 1 a ; do
    str+="${a}"

    if [ "${str}" = "${expect}" ] ; then
        echo "!!! found: ${str}"
        echo ">>> sending answer: ${answer}"
        echo "${answer}" >&3
        unset str
    fi

    if [ "$a" = $'\n' ] ; then
        echo -n "--- discarding input line: ${str}"
        unset str
    fi
done < <(./child.sh <${fifo})

rm ${fifo}

I just wrote that.. so it is not really failsafe or tested for solving specific problems.. So use at your own risk 8) Some line buffering problems may occur under some conditions..

But at least it worked in my test scenario..

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .