Search code examples
linuxbashcut

Return zero when cut command doesn't return any value


I have a scenario where

extract_content='60^123'

extract_count=$(echo $extract_content | cut -d^ -f1)

Then

extract_count='60' is what I achieve

Now sometimes

extract_content=?

Then I want

extract_count='0'

How can I achieve that using cut command


Solution

  • Don't use cut at all.

    extract_content='60^123'
    
    extract_count=0
    [[ $extract_content =~ ([[:digit:]]+)\^ ]] && extract_count=${BASH_REMATCH[1]}
    

    or

    [[ $extract_content =~ ([[:digit:]]+)\^ ]]
    extract_count=${BASH_REMATCH[1]:-0}
    

    or even

    extract_count=${extract_content%%^*}
    extract_count=${extract_count:-0}