Search code examples
linuxbashshellcronexpect

Bash+Expect script not running properly in crontab


I have a bash script that is supposed to run periodically. the script should connect to a remote SFTP server and get a file from there. Since this is a SFTP server I had to use expect with the bash script. the script runs well when I run it manually but fails when running via crontab. the problematic function is the get_JSON_file() please advise...

this is the code:

#!/bin/bash

export xxxxx
export xxxxx
export PATH=xxxxx

check_if_file_is_open(){
while :
do
    if ! [[ `lsof | grep file.txt` ]]
    then
        break
    fi
    sleep 1
done
}


get_JSON_file(){
/usr/bin/expect -f <(cat << EOF
spawn sftp -P port user@ip
expect "Password:"
send "password\r"
expect "$ "
send "get path/to/file/file.json\r"
send "exit\r"
interact
EOF
)
}


get_JSON_file
check_if_file_is_open
cp file.txt /path/to/destination/folder

Solution

  • To run a function within a shell script, no parentheses should be used.

    Your code then becomes:

    #!/bin/bash
    
    export xxxxx
    export xxxxx
    export PATH=xxxxx
    
    function check_if_file_is_open(){
    while :
    do
        if ! [[ `lsof | grep file.txt` ]]
        then
            break
        fi
        sleep 1
    done
    }
    
    
    function get_JSON_file(){
    /usr/bin/expect -f <(cat << EOF
    spawn sftp -P port user@ip
    expect "Password:"
    send "password\r"
    expect "$ "
    send "get path/to/file/file.json\r"
    send "exit\r"
    interact
    EOF
    )
    }
    
    
    get_JSON_file
    check_if_file_is_open
    cp file.txt /path/to/destination/folder