expect command or scripting language works with scripts that expect user inputs. It automates the task by providing inputs.
// We can install expect command using following if not installed
// On Ubuntu
$sudo apt install expect
// On Redhat based systems
$ yum install expect
First we write a script that will be needing inputs from users and then we will write another script using expect to automate the task.
#!/bin/bash echo "Enter your name" read $REPLY echo "Enter your age" read $REPLY echo "Enter your salary" read $REPLY
Ok, so let’s write down the script to answer questions of the above script.
#!/usr/bin/expect -f set timeout -1 spawn ./que.sh expect "Enter your name\r" send -- "I am Nikhil\r" expect "Enter your age\r" send -- "24\r" expect "Enter your salary\r" send -- "100k\r" expect eof
The first line defines the expect command path which is #!/usr/bin/expect .
On the second line of code, we disable the timeout. Then start our script using spawn command.
We can use spawn to run any program we want or any other interactive script. The spawn command is used to start a script or a program like the shell, FTP, Telnet, SSH, SCP, and so on.
The remaining lines are the Expect script that interacts with our shell script.
The last line if the end of file which means the end of the interaction.
First we have to make the file executable and then run it.You can do this by typing the following:
$ chmod +x ./ans.sh $ ./ans.sh
This will produce an output like this :
To build an expect script automatically, you can the use autoexpect command.autoexpect works like expect, but it builds the automation script for you. The script you want to automate is passed to autoexpect as a parameter and you answer the questions and your answers are saved in a file.
$ autoexpect ./que.sh
A file is generated called script.exp contains the same code as we did above with some additions.
if you run the file script.exp you will see the same answers that you provided.
- rev command in Linux with Examples
- for command in Linux with Examples
- look command in Linux with Examples
- more command in Linux with Examples
- mv command in Linux with examples
- until command in Linux with Examples
- apt-get command in Linux with Examples
- df command in Linux with Examples
- du command in Linux with examples
- pwd command in Linux with Examples
- col command in Linux with Examples
- dir command in Linux with examples
- top command in Linux with Examples
- cp command in Linux with examples
- ar command in Linux with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.