Skip to main content
3 of 3
deleted 252 characters in body
Rui F Ribeiro
  • 58k
  • 28
  • 156
  • 238

Build a command dynamically

I'm working on a script and I need to build the tar command dynamically.

Here are two examples to illustrate what I'm trying to do :

#!/bin/bash

TAR_ME="/tmp"

EXCLUDE=("/tmp/hello hello" "/tmp/systemd*" "/tmp/Temp*")
_tar="tar "`printf -- '--exclude="%s" ' "${EXCLUDE[@]}"`" -zcf tmp.tar.gz"
echo COMMAND: "${_tar}"
${_tar} "$TAR_ME"

echo -e "\n\nNEXT:\n\n"

EXCLUDE=("--exclude=/tmp/hello\ hello" "--exclude=/tmp/systemd*" "--exclude=/tmp/Temp*")
_tar="tar "`printf -- '%s ' "${EXCLUDE[@]}"`" -zcf test.tar.gz"
echo COMMAND: "${_tar}"
${_tar} "$TAR_ME"

I want to be able to use _tar as a command, I've been able to make it work with classic path, but I need it to work with spaces in folders' name. And every single time I got errors that look like :

COMMAND: tar --exclude="/tmp/hello hello" --exclude="/tmp/systemd*" --exclude="/tmp/Temp*"  -zcf tmp.tar.gz /tmp
tar: hello": Cannot stat: No such file or directory

COMMAND: tar --exclude=/tmp/hello\ hello --exclude=/tmp/systemd* --exclude=/tmp/Temp*  -zcf test.tar.gz 
tar: hello: Cannot stat: No such file or directory

Just one thing you need to know, I need my script to work on very old machines, meaning I can't use last bash features.

ShellCode
  • 235
  • 1
  • 2
  • 10