What worked for me is like this:
gv@debi64:$ ls -l *.sh
-rwxr-xr-x 1 root root 56376 Jan 20 12:40 bashtest.sh
-rwxr-xr-x 1 root root 2682 Dec 14 17:58 cpu.sh
-rwxr-xr-x 1 root root 3661 Dec 14 17:58 greptest.sh
-rwxr-xr-x 1 root root 1215 Dec 14 17:58 iconlist.sh
-rwxr-xr-x 1 root root 22096 Jan 20 11:22 inst.sh
-rwxr-xr-x 1 root root 141 Jan 18 09:21 oneshot.sh
-rwxr-xr-x 1 root root 154 Dec 27 17:48 remove.sh
-rwxr-xr-x 1 root root 2393 Dec 14 17:58 twoscreens.sh
$ ex[0]='--exclude=cpu.sh'
$ ex[1]='--exclude=inst.sh'
$ tar "${ex[@]}" -cvf backup.tar *.sh
bashtest.sh
greptest.sh
iconlist.sh
oneshot.sh
remove.sh
twoscreens.sh
As you can see the files cpu.sh and inst.sh are omited by the archive.
Similarly you could build your array like this :
exclude[0]='--exclude=/home/user/test1'
exclude[1]='--exclude=/home/user/test2'
exclude[2]='--exclude=/home/user/test3'
As an alternative, bellow method also worked for me without the need to store in array elements "--exclude" in front.
$ ex[0]='cpu.sh'
$ ex[1]='inst.sh'
$ IFS=,
$ excluded=$(eval echo "--exclude="{"${ex[*]}"})
$ unset IFS
$ tar "$excluded" -cvf backup.tar *.sh
The trick here is the second line that will add in front of each array element the word --excluded=
using brace expansion without requiring a loop into array elements.
In order brace expansion to work, array elements must be separated by comma and this is ensured by changing IFS to comma.
$ echo "$excluded"
--exclude=cpu.sh --exclude=inst.sh
--exclude-from
and create a file with your exclusions than dealing with arrays? – Jan 20 '17 at 11:38