简体   繁体   中英

how to detect newline characters as empty variables in bash?

I have following sample code in bash file, where I am trying to detect empty variables after I read them from an array. (Note: I am getting an array from other application to bash)

Problem is I am not able to detect newline characters using [[ -n "${var}" ]] or using [[ ${var} != "" ]]

Following is my bash code.

#!/bin/bash

function test0 {
  echo "........test 0 start........"
  newline='
'
  test_arr=("${newline}" "${newline}" "${newline}")
  echo "Array Size     --> ${#test_arr[@]}"
  echo "Array Content  -->  ${test_arr[@]}"

  aa=${test_arr[0]}
  bb=${test_arr[1]}
  cc=${test_arr[2]}

  aa="x"

  [[ -n "${aa}" && -n "${bb}" && -n "${cc}" ]] || {
    echo "ERROR : Empty aa or bb or cc."
    # exit 1
  }
  echo "........test 0 end........"
}

function test1 {
  echo "........test 1 start........"
  test_arr=("" "" "")
  echo "Array Size     --> ${#test_arr[@]}"
  echo "Array Content  -->  ${test_arr[@]}"

  aa=${test_arr[0]}
  bb=${test_arr[1]}
  cc=${test_arr[2]}

  aa="x"

  [[ -n "${aa}" && -n "${bb}" && -n "${cc}" ]] || {
    echo "ERROR : Empty aa or bb or cc."
    # exit 1
  }
  echo "........test 1 end........"
}

function main {
  echo "........MAIN start........"
  test0
  echo "--------------------------"
  test1
  echo "........MAIN end........"
}

main

Above code prints following output

........MAIN start........
........test 0 start........
Array Size     --> 3
Array Content  -->  
 
 

........test 0 end........
--------------------------
........test 1 start........
Array Size     --> 3
Array Content  -->    
ERROR : Empty aa or bb or cc.
........test 1 end........
........MAIN end........

My Expectation for test0 is also to throw Error "ERROR: Empty aa or bb or cc"

Is there any short way I can achieve this in bash (without using sed / awk etc. on variables)

Using regex, how about:

  pat=$'^\n*$'    # pattern to match zero or more newline characters
  if [[ $aa =~ $pat || $bb =~ $pat || $cc =~ $pat ]]; then
    echo "ERROR : Empty aa or bb or cc."
    # exit 1
  fi

in place of

  [[ -n "${aa}" && -n "${bb}" && -n "${cc}" ]] || {
    echo "ERROR : Empty aa or bb or cc."
    # exit 1
  }

If you want to detect whitespaces, tabs, carriage returns and newlines as an empty characters, assign pat to:

pat='^[[:space:]]*$'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM