Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing command line using argc and argv in expect

Tags:

expect

I have an expect routine, which needs to spawn a process and pass the command line arguments I passed to the expect routine to the spawned process.

My expect routine has the following line

spawn myProcess $argv

and when I call my expect routine I call it from the command line as follows

expect myRoutine <arg1> <arg2> <arg3>

When I do this, expect throws the following error

Can't open input file <arg1> <arg2> <arg3> for reading

However if I change my expect routine as follows

spawn myProcess [lindex $argv 0] [lindex $argv 1] [lindex $argv 2]

myProcess is spawned without any errors. However this is not useful to me, as I cannot guarantee that I would always have three arguments passed to the expect routine.

How do I pass command line arguments from the command line of a unix shell to the spawned process in expect?

like image 587
Prashant Avatar asked May 13 '15 05:05

Prashant


1 Answers

If you are not sure about the number of arguments which is going to be passed, then, you can make use of eval or argument expansion operator {*}.

If your Tcl's version is 8.5 or above,

spawn <program-name> {*}$argv

Else,

eval spawn <program-name> $argv

Lets consider the following Tcl program

cmdlinearg.tcl

#!/usr/bin/tclsh

set count 0;
if { $argc == 0 } {
        puts "No args passed :("
        exit 1
}
foreach arg $argv {
        puts "$count : $arg"
        incr count
}
puts "THE END"

This program will receive any number of command line arguments. To run this program, we execute the following command in the shell

dinesh@PC:~/stackoverflow$ tclsh cmdlinearg STACK OVER FLOW

which will give output as

0 : STACK
1 : OVER
2 : FLOW
THE END

Now, lets write one more program which will spawn this program along with any number of command line arguments.

MyProgram.tcl

#!/usr/bin/expect

# If your Tcl version is 8.4 or below
eval spawn tclsh $argv
expect eof
# If your Tcl version is 8.5 or above
spawn tclsh {*}$argv
expect eof

If suppose, you want to pass your program name itself as an argument, that is also possible.

# Taking the first command line arg as the program name and
# using rest of the args to the program
eval spawn [lindex argv 0] [ lrange $argv 0 end ]
expect eof
like image 199
Dinesh Avatar answered Jan 02 '23 13:01

Dinesh