Debanjan .Mukherjee Debanjan .Mukherjee - 1 year ago 74
Bash Question

compare substrings in Busybox ash

This is my first time on stackoverflow .I am facing an issue currently ,and sharing the details here.

I am currently building a POS automation script . The POS terminal have Shell Busybox ash . Thats why am not able to use the basic commands ,as those are not behaving same .
Below is the query :

[[ $I == $N$A ]] - this comparison is for exact match ,where $I is the bigger string and $N$A contains the substring of $I.
i have used [ -z ${I##$N$A* ] and [ “$I” == “$N$A”* ] syntax to compare the substring , but it fails and not behaving like it should.

Please guide if any one have any suggestion on this .
Please let me know if there is any online console for busybox ash where i can test some scripts .

Example Added -27-08-16

suppose -
the script deriving the value

$I = "Credit.saleApproved"

and i am passing the value for
$N= "Credit" and $A= ".sale"

So basically echo $N$A is a substring of echo $I
I am writing this pseudo logic for ur better understanding

If [[ $I == $N$A ]]
echo "sale is complete"
echo "sale is declined"

All i need is -->

1 . input : $I = Credit.saleApproved
$N$A =
Output :sale is complete

2.input : $I = Credit.sApproved
$N$A =
Output :sale is Declined

Answer Source

The Bourne Again SHell supports some comparisons that are not supported by other shells, such as Busybox ash. Some common pitfalls are enlisted here

Specifically comparison with [[ ... ]] are only supported by bash, as well as using a wildcard (*) in comparisons.

If you would like to match using ash, you could try these:

[ "$I" == "$N$A" ] # Match exactly
[ "$I" != "${I#$N$A}" ] # Starts with
[ "$I" != "${I%$N$A}" ] # Ends with

To check whether a string contains some other string, I can think of no easy way to do that with shell expressions, ash does not support string substitution like ${I/$N$A}. There are multiple tools to choose from, for example grep and sed.

Using grep you could do:

if echo $I|grep "$N$A" - > /dev/null; then ...

Using sed you could do:

[ -z $(echo "$I"|sed "/$N$A/d") ] # Contains

But there are many ways to achieve this.