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?
+(${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.