Finding the current directory in a bash script

I am trying to write a script that initializes my git bindings in different ways, whether my git repository is a submodule or just a regular repository. It currently looks like this:

# 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

      

However, when testing, it seems to always follow the route else

even if I'm in a submodule.

Is there something missing on this line for determining if my path contains the expected characters?

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

+3


source to share


2 answers


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

      

Backticks means running a command and getting its result, it pwd

is a command that prints the current directory; Mnemonic: print working directory '; =~

- coincidence operator. Or just use $PWD

:



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

      

0


source


This uses the POSIX parameter expansion (explained below) to determine if the current path ends in /.git/modules

:

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

      

More on expanding options (insert from 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.

      

For example,

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

      

0


source







All Articles