0

I can't get to work tar exclude with the bash script.

#!/bin/bash


CMD='tar --exclude=*.{db,log,token} -zcvf /home/pi/backup/2020.11.08-18.04.59.backup.tgz -P /home/pi/backup/test'
echo $CMD
sudo $CMD

however, if I ran the echo output command, it works.

tar --exclude=*.{db,log,token} -zcvf /home/pi/backup/2020.11.08-18.04.59.backup.tgz -P /home/pi/backup/test

I'm trying to exclude files based on file extension.

tar (GNU tar) 1.30

0
1

In bash you should use an array:

cmd=(tar --exclude='*'.{db,log,token} -zcvf /home/pi/backup/2020.11.08-18.04.59.backup.tgz -P /home/pi/backup/test)

echo "${cmd[@]}"

=> tar --exclude=*.db --exclude=*.log --exclude=*.token ...

"${cmd[@]}"
# etc

The '*' above is to guard against someone planting files named like --exclude=foo.log, --exclude=bar.log in the your current directory in order to trip your command ;-)

Notice that this has nothing to do with tar, but with your shell (bash) and with how it parses and expands its command lines; also, neither arrays nor brace expansions like {db,log,...} are supported in other shells like dash or busybox sh.

2
  • if I want to pass the db,log,token as variable, how do I use it EXC=db,log,token cmd=(tar --exclude='*'.{$EXC} -zcvf – BoomRamada Nov 8 '20 at 10:10
  • I would not use brace expansion at all in that case. exc=(db log token); cmd=(tar "${exc[@]/#/--exclude=*.}" ...); ...; "${cmd[@]}". What you're trying to do doesn't work because the brace expansion is performed before variable expansion in bash. You can make it work with eval but then you will have to double quote everything, turning it into a mess. – user414777 Nov 8 '20 at 10:50

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.