Bash Script commands inside a program
Please excuse me if this is too simple for you, but I really did my search before posting this question. I am trying to create my first bash script for auto connecting on my softether vpn. To manually connect I follow these steps;
sudo ./vpnclient start
sudo ./vpncmd
then it asks me a question of selections from 1 to 3, I pick 2 and hit enter. Then it asks me something else and I just hit enter. Then;
AccountConnect ofis
exit
sudo dhclient vpn_vpn_se
sudo ip route add X.X.X.X/32 via 192.168.1.1
exit
Now I this is my amateur script but I guess something is wrong because it comes to part where I am supposed to pick an option from 1 to 3 and it does nothing after that part.
#!/bin/bash
cd /home/burock/vpnclient
sleep 1
sudo ./vpnclient start
sleep 1
sudo ./vpncmd
sleep 1
printf "2\n"
sleep 1
printf "\n"
sleep 1
printf "AccountConnect ofis\n"
sleep 1
exit
sudo dhclient vpn_vpn_se
sleep 1
sudo ip route add 46.1.131.30/32 via 192.168.1.1
sleep 1
exit
Could you help me out? I guess it won't type "2" and hit enter because it is under vpncmd command. Or I am doing it all wrong... I also tried to give 1 second pause between each command. I am using Lubuntu btw, if it matters. Thanks in advance.
Solution 1:
Once you run a command like sudo ./vpncmd
, control doesn't return to your script until the command exits (or forks itself into the background). Only at that point do your printf
commands get executed, sending their output to the terminal as usual.
You can try instead something like
{ sleep 1
printf "2\n"
sleep 1
printf "\n"
sleep 1
printf "AccountConnect ofis\n"
} | sudo ./vpncmd
or (if the sleep
s aren't strictly necessary) just
printf '%s\n' 2 "" "AccountConnect ofis" | sudo ./vpncmd
and so on, but if that fails you may need to script the interactive session with something like expect
or autoexpect