【发布时间】:2019-10-13 08:56:46
【问题描述】:
我编写了一个脚本,用于替换包含此格式字符串的文件中版本号的最后 3 位
“版本-所有:255.24.788”
脚本有两种模式:普通模式和高级模式。常规模式只是进行必要的更改,将文件添加到 git 并提交它们。高级版会创建一个分支来进行这些更改、修改文件、添加、提交,然后返回到原来的工作分支。
我在运行脚本时观察到一个奇怪的行为。该脚本在第一次运行时有效,但在第二次运行时,它会停止提交结果并尝试更改分支,从而导致合并冲突。我不明白为什么脚本只会运行奇数次(第一次、第三次、第五次)而运行偶数次(第二次、第四次、第六次)时会失败。
我尝试改变变量的语法并用一个简单的替换 perl 调用
echo "test" > file1.txt
出于调试目的,它似乎工作正常。重新添加 perl 命令时,脚本似乎恢复了其奇怪的行为。
#!/bin/bash
# This script replaces last 3 digits of a version number in a file
# There are 2 modes for the script
# 1. Regular - no flag needed, requires 1 argument: a version number
# 2. Advanced - flag "-a" needs to be used followed by 3 arguments: version number, push repo name, remote repo name.
advanced_script=false
version="none"
if [ "$1" = "-a" ] ; then
advanced_script=true
fi
if [ "$advanced_script" = true ] ; then
if [ $# -ne 4 ] ; then
echo -e "ERROR: Please supply the following 3 arguments and try again.\n"
echo -e " 1. New version number\n"
echo -e " 2. Push repository name\n"
echo -e " 3. Remote repository name\n"
exit 1
fi
version="$2"
else
if [ $# -ne 1 ] ; then
echo -e "ERROR: Please supply version number and try again.\n"
exit 1
fi
version="$1"
fi
old_version_full="version-all:255.24.788"
old_version=${old_version_full##*all:}
new_version=${old_version%.*}
new_version+=".${version}"
current_branch=$(git branch | grep \* | cut -d ' ' -f2)
commit_string="Bump the version to $version"
if [ "$advanced_script" = true ] ; then
local_branch="new_$version"
remote_master="$4/master"
git stash
git checkout -b "$local_branch" "$remote_master"
fi
perl -i -pe"s/${old_version}/${new_version}/g" file1.txt
perl -i -pe"s/${old_version}/${new_version}/g" file2.txt
git add file1.txt
git add file2.txt
git status
git commit -m "$commit_string"
if [ "$advanced_script" = true ] ; then
git push "$3"
git checkout "$current_branch"
git stash apply
fi
【问题讨论】:
-
git stash有时什么都不做,也不会创建任何存储。如果是这种情况,您以后的git stash apply将应用一些 other 存储,如果有的话,或者只是失败;两者似乎都不是一个好主意。这可能与您看到的问题无关,但也可能是,因为您在此处没有minimal reproducible example,所以很难说。 -
可能不相关的问题:
.在 Perl 正则表达式中具有特殊含义,因此您的模式与您认为的不匹配。修复它和相关的代码注入错误如下:perl -i -spe's/\Q$o/$n/g' -- -o="$old_version" -n="$new_version" file1.txt -
提示:您可以将两个调用合并到
perl:perl -i -spe's/\Q$o/$n/g' -- -o="$old_version" -n="$new_version" file1.txt file2.txt