Search code examples
linuxbashsedgreprhel

Matching first substring within a variable in Bash


I have 2 variables value and backup with following values:

value = 'abc'

backup = urls://string1abc.com, urls://string1cde.com, urls://string1efg.com, urls://string1abc.com

I want to check the first substring before comma within the backup variable and then grep for for $value and if it matches then $test=PASS

In above example, $backup contains abc in the first and last substring. However, I only want to check the the first substring which is urls://string1abc.com

I have the following command but it checks for all substrings within backup

grep -qs $value $backup && test='PASS' || test='FAIL'

Solution

  • You can use parameter expansion:

    if [[ ${backup%%,*} = *"$value"* ]]; then 
        test=pass
    else
        test=fail
    fi