How to CD inside a SFTP connection where the connection is established using - Shell script How to CD inside a SFTP connection where the connection is established using - Shell script unix unix

How to CD inside a SFTP connection where the connection is established using - Shell script


I also faced this problem and was able to find the solution. The solution is right there in the man page of sftp. In the man page, you will find where it is written the format of using sftp like this:

sftp [options] [user@]host[:dir[/]]

Actually, two formats are given there but this is the one I wanted to use and it worked.

So, what do you do? You simply supply the username@host as seen there, then, without any space followed by : and the path you want to change to in the client/remote server in your script and that's all. Here is a practical example:

sftp user@host:/path/ 


If your script does, as you state somewhere in this page,

sftp $user@$host cd $directory

and then tries to do something else, like:

sftp $user@$host FOO

That command FOO will not be executed in the same directory $directory since you're executing a new command, which will create a new connection to the SFTP server.

What you can do is use the "batchfile" option of sftp, i.e. construct a file which contains all the commands you'd like sftp to do over one connection, for example:

$ cat commands.txtcd foo/barput foo.tgzlcd /tmp/get foo.tgz

Then, you will be able to tell sftp to execute those commands in one connection, by executing:

sftp -b commands.txt $user@$host

So, I propose your solution to be:

  • With user's input, create a temporary text file which contains all the commands to be executed over one SFTP connection, then
  • Execute sftp using that temporary text file as "batch file"

Your script would do something like:

echo "Directory in which to go:"read directorytemp=$( mktemp /tmp/FOOXXX )echo "" > $tempecho "cd $directory" >> $temp# other commandssftp -b $temp $user@$hostrm $temp


If you are trying to change the directory of the machine, try lcd