Bash:如何使用变量运行命令期望引号?

时间:2016-10-17 15:50:09

标签: git bash

我有一个git命令,我想在我的脚本中运行:

git filter-branch -f --env-filter "STUFF HERE IN QUOTES"

问题是,在我的脚本中,我动态创建由STUFF HERE IN QUOTES表示的字符串:

ENVFILTER=""
while read commit; do
    IFS="|" read date hash message <<< "$commit"
    DATE_NO_SPACE="$(echo "${date}" | tr -d '[[:space:]]')"
    COMMIT_ENV=$(cat <<-END
         if [ \$GIT_COMMIT = $hash ]
         then
         export GIT_AUTHOR_DATE="$DATE_NO_SPACE"
         export GIT_COMMITTER_DATE="$DATE_NO_SPACE"
         fi
    END
    )
    ENVFILTER="$ENVFILTER$COMMIT_ENV"
done < $tmpfile
git filter-branch -f --env-filter \'"$ENVFILTER"\' // <---------- does not work

基本上我从空字符串ENVFILTER开始,然后用其他字符串连接它以形成一堆if语句。我在运行实际命令的最后一步遇到了麻烦。我不知道如何使用预期的引号+插值来运行它。

=== UPDATE ===

在查看@chepner的答案并使用"$ENVFILTER"后,我现在可以成功运行该命令。所以答案是正确的。

但是,我的if语句(与引号无关)存在错误:

Rewrite eeb8860c13179c931a513a9ada76dc109324d790 (1/17)/opt/boxen/homebrew/Cellar/git/2.6.2/libexec/git-core/git-filter-branch: eval: line 313: syntax error near unexpected token `if'
/opt/boxen/homebrew/Cellar/git/2.6.2/libexec/git-core/git-filter-branch: eval: line 313: `     fi     if [ $GIT_COMMIT =  08a2d85f9412c67435929d80ccc5b914f3ad8547  ]'
env filter failed:      if [ $GIT_COMMIT =  59d13c174c34b6540f61585ef507abcef29ab22e  ]
     then
 export GIT_AUTHOR_DATE="2016-10-02T21:16:37-04:00"
 export GIT_COMMITTER_DATE="2016-10-02T21:16:37-04:00"
     fi     if [ $GIT_COMMIT =  08a2d85f9412c67435929d80ccc5b914f3ad8547  ]
     then
 export GIT_AUTHOR_DATE="2016-08-31T17:54:28-04:00"
 export GIT_COMMITTER_DATE="2016-08-31T17:54:28-04:00"
     fi     if [ $GIT_COMMIT =  d7801396f5fb1092beec3aa484361cd50ab35e9e  ]
     then
 export GIT_AUTHOR_DATE="2016-08-31T17:53:07-04:00"
 export GIT_COMMITTER_DATE="2016-08-31T17:53:07-04:00"
     fi     if [ $GIT_COMMIT =  7930e9be149a57229c9fc26ccffe1c6453317d70  ]
     then
 export GIT_AUTHOR_DATE="2016-08-31T17:48:03-04:00"
 export GIT_COMMITTER_DATE="2016-08-31T17:48:03-04:00"
     fi     if [ $GIT_COMMIT =  f0849b2de99ac37790eaf6e40c8980988e865c7c  ]
     then
 export GIT_AUTHOR_DATE="2016-08-31T17:46:33-04:00"
 export GIT_COMMITTER_DATE="2016-08-31T17:46:33-04:00"
     fi
[

它有什么问题吗?我不明白

1 个答案:

答案 0 :(得分:3)

假设ENVFILTER包含正确的代码,这就是您所需要的:

git filter-branch -f --env-filter "$ENVFILTER"

只要引用了扩展程序,ENVFILTER中的任何特殊字符都会按原样传递给git

那就是说,我会稍微清理一下发电机:

envfilter=
while IFS="|" read -r date hash message; do
    envfilter+="if [ \$GIT_COMMIT = \"$hash\" ]; then echo \"here\"; fi;"
done < "$tmpfile"
git filter-branch -f --env-filter "$envfilter"