1

I am trying to cut off all occurrences of a character from the end of a string.

The test script I came up with is:

#!/bin/bash
Input="/tmp/blah/bloh/////////////"

Desired="/tmp/blah/bloh"

cut='/'

result=${Input%%+(${cut})}

echo "          Input: ${Input}"
echo "Expected result: ${Desired}"
echo "         Result: ${result}"
echo "---------------------------------------"
echo -n "        Outcome: "

[ "${Desired}" = "${result}" ] && echo "Success!" || echo "Fail!"

Running this script via bash /tmp/test.sh gives the following output:

          Input: /tmp/blah/bloh/////////////
Expected result: /tmp/blah/bloh
         Result: /tmp/blah/bloh/////////////
---------------------------------------
        Outcome: Fail!

However, if I copy and paste the entire thing in my console I get the expected result of /tmp/blah/blah

What is going on here?

1
  • 1
    Replace #!/bin/bash with #!/bin/bash -i ;) Commented Aug 15, 2018 at 11:54

1 Answer 1

3

+(${cut}) is an extended pattern, which bash does not recognize by default. You need to enable the extglob option first.

$ shopt -s extglob
$ Input="/tmp/blah/bloh/////////////"
$ cut='/'
$ echo "${Input%%+(${cut})}"
/tmp/blah/bloh

You probably have extglob enabled in your interactive shell via your .bashrc or .bash_profile configuration file, but neither file is used for the non-interactive shell started by your script.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.