Awk

檢測可選函式參數(標量)

  • June 26, 2018

考慮這個腳本:

function alfa(bravo, charlie) {
 if (charlie)
   return "charlie good"
 else {
   return "charlie bad"
 }
}
BEGIN {
 print alfa(1, 1)
 print alfa(1, 0)
 print alfa(1, "")
 print alfa(1)
}

結果:

charlie good
charlie bad
charlie bad
charlie bad

awk 是否有辦法判斷何時沒有提供參數?

是的,你可以這樣做:

function alfa(bravo, charlie) {  
 if (charlie) {
   return "charlie good"
 }
 if (charlie == 0 && charlie == "") {
   return "charlie not provided"
 }
 if (!charlie && charlie != 0) {
   return "charlie null"
 }
 if (!charlie && charlie != "") {
   return "charlie 0"
 }
}

結果:

charlie good
charlie 0
charlie null
charlie not provided

awk沒有內置方法來檢查變數是否已初始化。你必須自己做:

function alfa(bravo, charlie) {
 if (charlie == 0 && !length(charlie))
   return "charlie bad"
 else {
   return "charlie good"
 }
}
BEGIN {
 print alfa(1, 1)
 print alfa(1, 0)
 print alfa(1, "")
 print alfa(1)
}

一般方式:

var == 0 && !length(var)

未初始化的變數和 0 導致var == 0被評估為真,!length(var)排除了 時的情況var = 0

引用自:https://unix.stackexchange.com/questions/359224