space_voyager
space_voyager

Reputation: 2034

Bash how to include a command that has quotation marks as a variable?

In my bash script, in several places I need to run the command

rsync [stuff] --exclude={"/mnt/*","/proc/*"} [source] [destination]

To avoid typing out the whole list, I want to pack the option --exclude={"/mnt/*","/proc/*"} into a variable called EXCLUDES such that I can type in my script:

rsync [stuff] "$EXCLUDES" [source] [destination]

What is the proper way to achieve this?

Upvotes: 0

Views: 183

Answers (1)

chepner
chepner

Reputation: 532268

Use an array:

EXCLUDES=(
  --exclude="/mnt/*"
  --exclude="/proc/*"
)
rsync [stuff] "${EXCLUDES[@]}" [source] [destination]

or a here-doc with the --exclude-from option:

rsync [stuff] --exclude-from - [source] [destination] <<EOF
/mnt/proc/*
/proc/*
EOF

I would recommend against using brace expansion in a script. Your text editor should make it easy to quickly duplicate repeated strings, and the the resulting script will be more readable. Brace expansions are intended for interactive use.

Upvotes: 2

Related Questions