I have a bash script to get a file from a remote sftp site, the file has a space in the name (this can't be changed)
!/bin/bash
filename="$(echo "ls -tr" | sftp -i ~/.ssh/id_rsa username@host:/tmp/myfiles | tail -n 1)"
cmd="get /tmp/myfiles/$filename"
echo "'$cmd'" | sftp -i ~/.ssh/id_rsa username@host:/tmp/myfiles
I get the error
user on host ~/scripts in /home
14:32:45 » ./get_files.sh
Connected to host.
get /tmp/myfiles/User data_20230330_103101.csv
Connected to host.
Changing to: /tmp/myfiles
Invalid command.
sftp> 'get /tmp/myfiles/User data_20230330_103101.csv '
File "get /tmp/myfiles/User data_20230330_103101.csv " not found.
I can see it complains about whitespace after the filename, but can't figure out where this is coming from? I can log onto the sftp server and ls which shows the file is present, but not with the trailing whitespace that I can't find where it comes from.
You're quoting the wrong thing, and your filename variable has whitespace on the end.
Change
cmd="get /tmp/myfiles/$filename"
to
shopt -s extglob # note, this requires a *bash* script not a *sh* script
filename=${filename%%+([[:space:]])} # remove trailing spaces from filename
cmd="get '/tmp/myfiles/$filename'"
and then change echo "'$cmd'"
to echo "$cmd"