I have to set in crontab an sh script that prompts user to answer before executing. But sometimes the question needs "Yes" or "No" answer and sometimes the same script waits for "Force" or "Abort". I can't modify this script, so i need to make my script to launch the first one, catch the prompt output text and check the prompt text to answer "Yes" or "Force" automatically. I've tested something like this but doesn't work :
if command.sh | grep 'Force' =0
then echo "Force"
else echo "Yes"
fi
Thank you for your advices or help :)
CodePudding user response:
As you didn't provide any sample of command.sh
output then the following code is only a guess. It should do the job though, provided that you find something to match when you have to reply Yes
# define the named pipes (making them almost unique)
id=$(uuidgen)
cmd_in="/tmp/${0##*/}-$id-0"
cmd_out="/tmp/${0##*/}-$id-1"
mkfifo "$cmd_in" "$cmd_out"
# set command.sh to listen to "$cmd_in" and write to "$cmd_out"
./command.sh < "$cmd_in" > "$cmd_out" &
# If we write directly to "$cmd_in", the pipe will be closed.
# That doesn't happen when writing to a file handle.
exec 3> "$cmd_in"
exec 4< "$cmd_out"
while read -r
do
# debug info
printf '%s\n' "$REPLY"
# reply according to the question
case $REPLY in
*Force*)
echo "Force" >&3
break
;;
*SomethingThatMatchesForYes*)
echo "Yes" >&3
break
;;
esac
done <&4
# waiting for command.sh to complete
wait
# do some cleaning
exec 3>&-
exec 4<&-
echo rm -f "$cmd_in" "$cmd_out"
There are some cases for which the previous code won't work:
command.sh
prompts the questions tostderr
(=> can be fixed)- The questions don't end with a newline (=> no easy fix)
command.sh
tests for an interactive shell (=> no fix)
CodePudding user response:
Finally I tried a simpler solution and it seems working as expected
command.sh << EOF
Force
y
EOF
Thank for your help