动态构建命令

She*_*ode 9 bash tar string shell-script

我正在编写一个脚本,我需要tar动态构建命令。

这里有两个例子来说明我正在尝试做的事情:

#!/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"
Run Code Online (Sandbox Code Playgroud)

我希望能够_tar用作命令,我已经能够使其与经典路径一起使用,但是我需要它与文件夹名称中的空格一起使用。每次我遇到如下错误时:

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
Run Code Online (Sandbox Code Playgroud)

你需要知道的一件事是,我需要我的脚本在非常旧的机器上工作,这意味着我不能使用最后的 bash 功能。

Kus*_*nda 12

不要尝试制作可执行字符串。而是在数组中构建参数并在调用时使用它tar(您已经正确地为 使用了数组EXCLUDE):

#!/bin/bash

directory=/tmp

exclude=( "hello hello" "systemd*" "Temp*" )

# Now build the list of "--exclude" options from the "exclude" array:
for elem in "${exclude[@]}"; do
    exclude_opts+=( --exclude="$directory/$elem" )
done

# Run tar
tar -cz -f tmp.tar.gz "${exclude_opts[@]}" "$directory"
Run Code Online (Sandbox Code Playgroud)

与/bin/sh:

#!/bin/sh

directory=/tmp

set -- "hello hello" "systemd*" "Temp*"

# Now build the list of "--exclude" options from the "$@" list
# (overwriting the values in $@ while doing so):
for elem do
    set -- "$@" --exclude="$directory/$elem"
    shift
done

# Run tar
tar -cz -f tmp.tar.gz "$@" "$directory"
Run Code Online (Sandbox Code Playgroud)

需要注意的引用$@的sh代码和两个${exclude[@]}和${exclude_opts[@]}的bash代码。这可确保将列表扩展为单独引用的元素。

有关的: