Home > Back-end >  Can't index of the "#[hello]" in bash
Can't index of the "#[hello]" in bash

Time:08-26

The following index_of function doesn't work for all cases:

#!/bin/bash

index_of() {
    local string="$1"
    local search_string="$2"
    
    local prefix=${string/${search_string}*/}
    
    local index=${#prefix}
     
    if [[ index -eq ${#string} ]];
    then
        index=-1
    fi
    
    printf "%s" "$index"
}

a='#[hello] world'

b=$(index_of "$a" "world")
echo "A: $b"

b=$(index_of "$a" "hello")
echo "B: $b"

b=$(index_of "$a" "#[hello]")
echo "C: $b"

Here is the output:

A: 9
B: 2
C: -1

The A and B is correct, but the C is incorrect.

The C should be 0 instead of -1.

What's wrong in the index_of function and how to fix the C index?

CodePudding user response:

#!/bin/bash

index_of() {
    local string="$1"
    local search_string="$2"

    local prefix=${string/${search_string}*/}

    local index=${#prefix}

    if [[ $index -eq ${#string} ]];
    then
        index=-1
    fi

    printf "%s" "$index"
}

a='#[hello] world'

b=$(index_of "$a" "world")
echo "A: $b"

b=$(index_of "$a" "hello")
echo "B: $b"

b=$(index_of "$a" "\#\[hello\]")
echo "C: $b"

result

A: 9
B: 2
C: 0
  • Related