For example, I want to execute the following within a shell script:

tar cvpzf /destination/backup.tgz /directory\ one /directory\ two

I wish to assign the list of paths (with whitespaces in them) to a variable at the top portion of a script, for easy maintenance.

How would one assign "/directory\ one /directory\ two" to a variable and then pass it on later, for example, to tar, i.e.:

tar cvpzf /destination/backup.tgz $backup_dirs

without causing tar to interpret /directory and one as separate entities, just how it would not do so when one executes it in the command line?

  • Are you familiar with xargs? – Fiximan Sep 4 '15 at 10:51

Just quote it:

dir1="directory 1"
dir2="directory 2"

tar cvpzf /destination/backup.tgz "$dir1" "$dir2"

Or, if your shell supports it (bash, which you've tagged your question with, does but sh, which you are using in your script doesn't) use arrays:

targets=( "directory 1" "directory 2" )
tar cvpzf backup.tgz "${targets[@]}"
| improve this answer | |
  • Thank you for this straightforward solution. Most readable too as one gets to avoid typing in escape characters. One gets to use newline too as delimiters for the directory strings. My /bin/sh points to dash which supports arrays, but I believe it's probably better to explicitly indicate #!/bin/bash. – silvernightstar Sep 5 '15 at 11:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.