Search code examples
bashgitvariablesgit-bashstring-operations

How to perform multiple string operations on Bash variable with least steps?


I have gitbash installed in Windows 10 64bit, but I assume the solution I am asking will work in both Linux Git and Win GitBash.

I have defined the BRNCH variable to do multiple commit and merge operations involving the current branch, so I have declared current branch like below:

BRNCH=`git branch --show-current`

Now I want to get the Ticket ID (which is usually the capital of branch name discarding any versions like -v1,-v2 .... and keeping the digits as it is) from the branch name in the same current branch variable, and I am trying below, but this doesn't work:

echo ${BRNCH%-*^^}

So for eg. if the branch name I have is abc-123-v3 the above code which is expected to perform multiple string operations and print ABC-123, doesn't even do single operation, but this works and gives me abc-123:

echo ${BRNCH%-*}

I don't know very deep about Bash coding, so I assumed something like nested brace pairs with order precedence(this could be possible future enhancement in Bash and GitBash :)) might work and applied this, but that too didn't work:

echo ${{BRNCH%-*}^^}

So how to do multiple string operations on bash variable with just one or fewest lines of code and steps ?


Solution

  • So for eg. if the branch name I have is abc-123-v3 the above code which is expected to perform multiple string operations and print ABC-123

    What's wrong with

    v=${BRNCH%-*}
    echo ${v^^}
    

    ?

    You can hide the temp and save yourself later trouble,

    ticketfor() { local v=${1%-*}; echo ${v^^}; }
    
    ticketfor $BRNCH