Search code examples
bashsshexpect

Is there any way to send if else statement to remote server while using expect command in shell script?


I want to connect a remote server via ssh using expect and check specific directory exists if not create file if exists create subsequent directory. I can connect remote server and send line commands but when it comes to statement like if else it doesn't accept.

Here is my code snippet. It only connects remote and exits.

#!/usr/bin/expect -f

set timeout 120
spawn ssh user@remoteIP
expect "*?assword:"
send "remote password"
expect "$ "
set name "b"
send "if [ -d /path/to/remote/directory/$name ]; then
    set i 1
  while [ -d /path/to/remote/directory/$name$i ]; do
      let i++
    done
   set name $name$i
  fi"
send -- "mkdir -p /path/to/remote/directory/$name\r"
expect "$ "
send -- "exit\r"
expect eof

Solution

  • The code you send to the shell needs to be valid shell script. You can't expect the shell to update your Expect variables, or vice versa.

    Try the following:

    send "i=''
    while \[ -d /path/to/remote/directory/$name\$i ]; do
       let i++
    done
    mkdir -p /path/to/remote/directory/$name\$i\r"
    

    The variable $name is your Expect variable, while \$i should be passed through to the shell as literally $i. Similarly, [ needs to be escaped to avoid executing it as an Expect construct.

    For completeness, here is the full script with this change.

    #!/usr/bin/expect -f
    
    set timeout 120
    spawn ssh user@remoteIP
    expect "*?assword:"
    send "remote password"
    expect "$ "
    set name "b"
    send "i=''
    while \[ -d /path/to/remote/directory/$name\$i ]; do
       let i++
    done
    mkdir -p /path/to/remote/directory/$name\$i\r"
    expect "$ "
    send -- "exit\r"
    expect eof