Search code examples
linuxbashsshtty

how to do if else in ssh pseudo-tty allocation to remote server


I tried to ssh with pseudo-tty allocation to remote server using the following bash script;

ssh -t -t user@remote-host
if [ -d "/test/dir_test" ]; then
  sudo chown -R user:admin /test/dir_test/
  sudo rm -rf /test/dir_test/*
else        
  sudo mkdir /test/dir_test/
fi

that checks if /test/dir_test exists on remote-host, if not create such dir test/dir_test on remote-host; but the script does not work, I am wondering how to do it using ssh with pseudo-tty allocation in this case.


Solution

  • You will have to quote the commands that is to be sent to the server like so:

    ssh -t -t user@remote-host "
    if [ -d '/test/dir_test' ]; then
      sudo chown -R user:admin /test/dir_test/
      sudo rm -rf /test/dir_test/*
    else        
      sudo mkdir /test/dir_test/
    fi"
    

    Be aware that sudo needs a password unless otherwise specified in its configuration.