I am trying to use cURL to upload files with spaces in their filenames onto a dedicated server. I am using bash. In a previous project, I just gave up, removing all spaces from filenames. This is not feasible for this project.
Running cURL in verbose mode suggests that it stops when it reads my local file path:
curl -X PUT -u $USER:$PASS --data-binary @"$LOCAL_FILE" "$SERVER/remote.php/dav/files/$USER/$REMOTE_DIR/$REMOTE_FILE"
where $LOCAL_FILE is a path to a file on my local machine (with spaces), and $REMOTE_FILE also has spaces.
This gives:
Warning: Couldn't read data from file "/Users/my_account/somepath/with
Warning: spaces
which implies the command is taking "/Users/my_account/somepath/with"
and "spaces"
as two separate paths.
How can I solve this?
My full code:
#!/bin/bash -ex
# Local dir - note space in path
IMAGES_DIR="/Users/my_account/somepath/with spaces"
# Remote server, and credentials
SERVER="http://myserver"
REMOTE_DIR="mydir"
USER="myname"
PASS="mypass"
FILE="$1"
LOCAL_FILE="$IMAGES_DIR/$FILE"
REMOTE_FILE=urlencode $FILE
# Move file to the server
curl -v -X PUT -u $USER:$PASS --data-binary @"$LOCAL_FILE" "$SERVER/remote.php/dav/files/$USER/$REMOTE_DIR/$REMOTE_FILE"
# Check that file has made it
echo 'Waiting for file to be on server'
until [ $result > 0 ]
do
result=$(curl -I "$SERVER/remote.php/dav/files/$USER/$REMOTE_DIR/$REMOTE_FILE" -u $USER:$PASS 2>/dev/null | grep Content-Length | awk -F ': ' '{print $2}')
echo "."
sleep 2
done
echo "File $FILE is now on server."
urlencode() {
# urlencode <string>
old_lc_collate=$LC_COLLATE
LC_COLLATE=C
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf '%%%02X' "'$c" ;;
esac
done
LC_COLLATE=$old_lc_collate
}