簡體   English   中英

如何在 bash 中將換行符檢測為空變量?

[英]how to detect newline characters as empty variables in bash?

我在 bash 文件中有以下示例代碼,我試圖在從數組中讀取空變量后檢測它們。 (注意:我從其他應用程序獲取一個數組到 bash)

問題是我無法使用[[ -n "${var}" ]]或使用[[ ${var} != "" ]]檢測換行符

以下是我的 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

上面的代碼打印在 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........

我對 test0 的期望也是拋出錯誤"ERROR: Empty aa or bb or cc"

有什么捷徑可以在 bash 中實現(不使用sed / awk等變量)

使用正則表達式,怎么樣:

  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

代替

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

如果要將空格、制表符、回車符和換行符檢測為空字符,請將pat分配給:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM