Search code examples
sshwhile-loopexpectfile-existsnot-exists

How to run "file exist" function (expect/tcl) as condition during a while loop?


I know that this is a similar question to other posts but after trying variants of their code I have not been able to get the result I want. The expect script logs in, submits a cluster job and waits for the resulting file to be written. I want to check periodically for the result file and move on in my expect script after the file is in the directory. When I run the following code, the [file exists outgraph.json] never appears to equal 1 even after I see the file in another ssh session. I think I am overlooking something simple but cannot figure out why it never detects the file during the loop resulting on the expect script never moving forward.

#Attempt 1
#Spawning and logging in
send "qsub -v QUERY=$query run\_query.pbs\r"
while {true} {
    after 2000
    if {[file exists outgraph.json] == 1} {
    break;
    }
    puts [file exists outgraph.json]
}
expect "$ "
send "rm -rf tmp1\r";
expect "$ "
send "rm input.fa\r";
expect "$ "
send "exit\r"
# moving file with sftp

#Attempt 2
# spawning and logging in
send "qsub -v QUERY=$query run\_query.pbs\r"
set fexist [file exists outgraph.json]
while {$fexist == 0} {
    after 2000;
    set fexist [file exists outgraph.json]
    puts $fexist
} 
expect "$ "
send "rm -rf tmp1\r";
expect "$ "
send "rm input.fa\r";
expect "$ "
send "exit\r"
# moving file with sftp

Solution

  • The problem is because of file exists. It checks the file path present or not, only in the local machine wherever you are running the Expect script, not in the remote directory.

    #This is a common approach for few known prompts
    #If your device's prompt is missing here, then you can add the same.
    set prompt "#|>|\\\$ $"; # We escaped the `$` symbol with backslash to match literal '$'
    
    set filename outgraph.json
    set cmd "(\[ -f $filename ] && echo PASS) || echo FAIL" 
    send "$cmd\r"
    expect {
        "\r\nPASS" { puts "File is available";exp_continue}
        "\r\nFAIL" { puts "File is not available";exp_continue}
        -re $prompt 
    }