简体   繁体   English

如何在 bash 中将换行符检测为空变量?

[英]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.我在 bash 文件中有以下示例代码,我试图在从数组中读取空变量后检测它们。 (Note: I am getting an array from other application to bash) (注意:我从其他应用程序获取一个数组到 bash)

Problem is I am not able to detect newline characters using [[ -n "${var}" ]] or using [[ ${var} != "" ]]问题是我无法使用[[ -n "${var}" ]]或使用[[ ${var} != "" ]]检测换行符

Following is my bash code.以下是我的 bash 代码。

#!/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上面的代码打印在 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"我对 test0 的期望也是抛出错误"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)有什么捷径可以在 bash 中实现(不使用sed / awk等变量)

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分配给:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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