在bash脚本中检测当前目录

3

我正在尝试编写一个脚本,根据我的git repo是子模块还是普通存储库来初始化我的git hooks。它目前的样子如下:

# Get to root directory of client repository
if [[ ":$PATH:" != *":.git/modules:"* ]]; then # Presumed not being used as a submodule
  cd ../../
else
  cd .. # cd into .git/modules/<nameOfSubmodule> (up one level from hooks)
  submoduleName=${PWD##*/} # Get submodule name from current directory
  cd ../../../$submoduleName  
fi

然而,在测试中,即使我在子模块中,它似乎总是走 else 的路线。

这行代码中是否有什么我忽略的东西,以确定我的路径是否包含了预期的字符?

if [[ ":$PATH:" != ":.git/modules:" ]]


你是否混淆了 $PATH$PWD - choroba
2个回答

0
if [[ "`pwd`" =~ \.git/modules ]]

反引号意味着运行命令并获取其输出,pwd是打印当前目录的命令;助记符:打印工作目录;=~是匹配操作符。或者简单地使用$PWD

if [[ "$PWD" =~ \.git/modules ]]

“$(命令替换)”比“反引号”更受青睐(考虑嵌套、可读性)。此外,当您可以使用“$PWD”时,无需调用外部命令“pwd”。 - randomir
哦,你的正则表达式是错误的(应该是“.git/modules$”)。 - randomir
$() is a bashism which I usually avoid. But you're right about \. - phd
1
$()POSIX 兼容不是 bashism - randomir
[[ foo =~ bar ]]是Bashism。Bash比较使用双方括号的表示法,并支持正则表达式匹配。POSIX不支持正则表达式匹配。 - Adam Katz
显示剩余2条评论

0

这里使用 POSIX 参数扩展(下面会解释)来确定当前路径是否以 /.git/modules 结尾:

if [ "$PWD" != "${PWD%/.git/modules}" ]

更多关于参数扩展的内容(从{{link1:dash(1)}}粘贴):

 ${parameter%word}     Remove Smallest Suffix Pattern.  The word is expanded
                       to produce a pattern.  The parameter expansion then
                       results in parameter, with the smallest portion of the
                       suffix matched by the pattern deleted.

例如:

FOO="abcdefgabc"
echo "${FOO%bc}"    # "abcdefga"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接