shellbusybox

compare substrings in Busybox ash


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

Suppose [[ $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 as it should.

Is there any online console for busybox ash where I can test some scripts?

Example

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 your better understanding.

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

All I need is -->

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

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

Solution

  • 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.