swagrov
swagrov

Reputation: 1460

Expect tcl "file exists" function failing even though "ls" shows file

I spawn a shell instance with spawn sh and I run some commands to generate files. I then use verify_file_exists below to check that they were created. Using file exists always fails though! I have edited the procedure below to further illustrate my problem. I explicitly create hello.txt and check for it's existence, but it always fails.

proc verify_file_exists {filename} {
    send "touch hello.txt\r"
    if {[file exists hello.txt]} {
        puts "hello.txt found\r"
    } else {
        puts "Failed to find hello.txt\r" # Always fails
        exit 1
    }
}

I tried something else too: I put an interact ++ return statement right before my call to verify_file_exists and that puts me in the sh instance. I then run touch hi.txt, then run expect and enter an expect instance. Then if I run file exists hi.txt I do get a positive response of 1! So this can't be a permission issue, right?

If I do the same thing as above but manually touch hello.txt, the procedure still fails at the file exists line.

Why is file exists not working as expected?

NOTE: Putting quotes around hello.txt does not solve the issue.

Upvotes: 2

Views: 3590

Answers (1)

pynexj
pynexj

Reputation: 20688

After send, you need to wait for the next shell prompt to show up which means the last command has completed. That's why send is usually followed by expect. For a quick test you can also add a sleep 1 after send.

Another possibility is that the Expect process' current dir is not the same as the spawned shell process' current dir.

A simple example for both:

[STEP 101] $ cat example.exp
proc expect_prompt {} {
    expect -re {bash-[.0-9]+[#$] $}
}

spawn bash --norc
expect_prompt

send "rm -f foo bar && touch foo\r"
expect_prompt
if { [file exists foo] } {
    send "# found foo!\r"
    expect_prompt
}

send "mkdir -p tmp && cd tmp && rm -f bar && touch bar\r"
expect_prompt
if { ! [file exists bar] } {
    send "# where's bar?\r"
    expect_prompt
}

send "exit\r"
expect eof
[STEP 102] $ expect example.exp
spawn bash --norc
bash-4.4$ rm -f foo && touch foo
bash-4.4$ # found foo!
bash-4.4$ mkdir -p tmp && cd tmp && rm -f bar && touch bar
bash-4.4$ # where's bar?
bash-4.4$ exit
exit
[STEP 103] $

Upvotes: 2

Related Questions