我在归档期间使用tar --transform
SSH 调用根据数组 DOCUMENTNAMES 重命名文档。
tar -uvf /tmp/$TARGET''TVL_document.tgz'' --transform='s|'\${doc}'|'\$docname'|' -C /appl-doc/a-mc-acc-dms/DATA \${doc}
如果 DOCUMENTNAMES 不包含空格(例如“application.pdf”),我可以获得 tar 输出。对于带有空格的 DOCUMENTNAMES(例如“project form.pdf”),shell 无法正确展开它,并且出现错误tar invalid transform expression
如何--transform='s|'\${doc}'|'\$docname'|'
以正确转义 DOCUMENTNAMES 中的空格的方式转义序列?
完整代码:
DOCUMENTNAMES=("project form.pdf" "application.pdf")
# SSH to Linux fileshare to create tar
sshpass -p $IPA_PASS ssh -tt -o StrictHostKeyChecking=no $IPA_NAME@$TARGET "sudo su - jboss <<'EOF'
# create an empty tar
tar -cvf /tmp/$TARGET''TVL_document.tgz'' -T /dev/null
# transfer local array to remote
eval `typeset -p DOCUMENTNAMES`
index=0
for doc in "${DOCUMENTIDS[@]}"
do
docname=\${DOCUMENTNAMES[\$index]}
# Update tar with one document at a time and update name using transform
tar -uvf /tmp/$TARGET''TVL_document.tgz'' --transform='s|'\${doc}'|'\$docname'|' -C /appl-doc/a-mc-acc-dms/DATA \${doc}
index=$((index+1))
done
EOF
"
答案1
看起来你想要:
DOCUMENTNAMES=("project form.pdf" "application.pdf")
# never pass password on the command line. Here passing it via an env var
# instead
SSHPASS=$IPA_PASS sshpass -e \
ssh -o StrictHostKeyChecking=no "$IPA_NAME@$TARGET" '
sudo -Hu jboss bash' << EOF
# pass variables across by dumping their definition on the client shell
# into the code interpreted by the remote shell
$(typeset -p TARGET DOCUMENTNAMES DOCUMENTIDS)
# rest in a heredoc with quoted delimiter so no expansion happens.
$(cat << 'END_OF_SCRIPT'
# never put files with fixed name in world writable directories
# here using a ~/tmp dir instead. You could also use things like:
# tmpdir=$(mktemp -d) || exit
tmpdir=~/tmp
tarfile=$tmpdir/${TARGET}TVL_document.tgz
mkdir -m 700 -p ~/tmp || exit
# create an empty tar
tar -cvf "$tarfile" -T /dev/null
index=0
for doc in "${DOCUMENTIDS[@]}"
do
docname=${DOCUMENTNAMES[index]}
tar -uvf "$tarfile" --transform="s|$doc|$docname|" -C /appl-doc/a-mc-acc-dms/DATA "$doc"
(( index++ ))
done
END_OF_SCRIPT
)
EOF