Score:1

Bash script variable with a space

jp flag

I try to write a bash script for copying data from one folder to another.

Source="/My Images/"
Target=/Transfer/Media/
rsync -avu --progress $Source $Target

The problem is, that the script can not find the folder "/My Images/", because there is a space between those two words.

How do I tell the variable Source to accept this folder name?

Raffa avatar
jp flag
Double quote `"$Source"` ... And as a good measure `"$Target"` as well as you should get into the habit of quoting parameters in your scripts ... i.e. `rsync -avu --progress "$Source" "$Target"`
Score:3
jp flag

How do I tell the variable Source to accept this folder name?

It's not assigning that parameter:

Source="/My Images/"

but rather its expansion:

rsync -avu --progress $Source $Target

As it appears you already know that quoting the path/string "/My Images/" is necessary to handle the space in it.

You will also need to quote the parameter/variable containing it when you use it in the command to prevent word splitting by the shell like so:

rsync -avu --progress "$Source" "$Target"

You should get into the habit of double quoting all parameters in your scripts.

I assume you are using rsync locally on the same machine, but if you are using it to synchronize files to a remote machine using ssh for example, then you might need to double quote/escape ... See for example: Using scp to copy a remote file containing spaces requires double space escaping. Why?

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.