我真的在努力编写 Bourne shell 脚本。基本上,我尝试检测一个名为“ref”的变量的三种输入格式:
- ref="refs/head/.*"(即以“refs/head/”开头,我对最后的位感兴趣,在斜杠之后)
- ref="refs/tags/.*"(即以“refs/tags/”开头 我对最后的位感兴趣,在斜杠之后)
- 其他所有内容(即忽略所有不以“refs/head/”或“refs/tags/”开头的内容)
例如,
如果 ref="refs/head/master",设置 TAG="master"
如果 ref="refs/tags/0.2.4",设置 TAG="0.2.4"
对于其他所有内容,设置 TAG=""
现在我在 bash shell 中写了一些东西,但我真的很难将它转换为 Bourne (#!/bin/sh):
#!/bin/bash
#
#This works!
#
TAG=""
re='^refs/head/.*' #regex: begins with refs/head/, ends with anything
re2='^refs/tags/.*' #regex: begins with refs/tags/, ends with anything
if [[ $ref =~ $re ]]; then
#do nothing - OK
true #NOP
else
#check if it's a tag update
if [[ $ref =~ $re2 ]]; then
TAG=${$ref##*/} #looks worse that it is: http://stackoverflow.com/questions/3162385/how-to-split-a-string-in-shell-and-get-the-last-field
fi
exit 0
fi
echo $TAG
我花了很长时间才 a) 编写了这个程序并且 b) 找出了为什么我的程序变得疯狂 - 结果我需要 #!/bin/sh 而不是 #!/bin/bash
如何将其转换为 sh?也许其他人对我的正则表达式体操有更优雅的解决方案?
更新:
感谢到目前为止的回答(尤其是@gboffi)。我想我快到了。
我现在只需要知道 $TAG 是来自“refs/head/”、“refs/tags/”还是两者都不是。我试图修改一些答案,但真的在 sh 上挣扎。我需要离开并从基本原理中了解更多关于 sh 的知识,而不是试图破解它。
更新 2:
所以经过一夜的 sleep ,我在大约 20 分钟内弄明白了。这是我的解决方案:
#!/bin/sh
ref="refs/asdf/master"
TAG=""
TAG="${ref#refs/heads/}"
if [ "$ref" != "${ref#refs/heads/}" ]; then
echo "heads"
echo $TAG
else
TAG="${ref#refs/tags/}"
if [ "$ref" != "${ref#refs/tags/}" ]; then
echo "heads"
echo $TAG
else
TAG=""
fi
fi
echo "--->$TAG"
我确信有一个更优雅的解决方案;但我只是没有时间!
最佳答案
这是一个函数,定义在 dash
(sh
的 linux 版本)
% dash
$ tag() {
> TAG=""
> [ "$1" != "${1#refs/head/}" ] && TAG="${1#refs/head/}"
> [ "$1" != "${1#refs/tags/}" ] && TAG="${1#refs/tags/}"
> echo "$TAG"
>}
$ tag poldo
$ tag refs/head/poldo
poldo
$ tag refs/tags/pippo
pippo
$ tag to093u0refs/head/poldo
$exit
%
关于linux - 使用正则表达式将 bash 脚本转换为 sh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27411632/