Bash

如何測試變數是否為空或僅包含空格?

  • January 11, 2022

以下 bash 語法驗證是否param不為空:

[[ !  -z  $param  ]]

例如:

param=""
[[ !  -z  $param  ]] && echo "I am not zero"

沒有輸出和它的罰款。

但是當param除了一個(或多個)空格字元之外為空時,情況就不同了:

param=" " # one space
[[ !  -z  $param  ]] && echo "I am not zero"

輸出“我不是零”。

如何更改測試以將僅包含空格字元的變數視為空?

首先,請注意該-z測試明確用於:

字元串的長度為零

也就是說,僅包含空格的字元串在 下應該為真-z,因為它的長度不為零。

您想要的是使用模式替換參數擴展從變數中刪除空格:

[[ -z "${param// }" ]]

這會擴展param變數並替換模式的所有匹配項 (a single space) with nothing, so a string that has only spaces in it will be expanded to an empty string.

`—

The nitty-gritty of how that works is that ${var/pattern/string} replaces the first longest match of pattern with string. When pattern starts with / (as above) then it replaces all the matches. Because the replacement is empty, we can omit the final / and the string value:

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. … If string is null, matches of pattern are deleted and the / following pattern may be omitted.

After all that, we end up with ${param// } to delete all spaces.

Note that though present in ksh (where it originated), zsh and bash, that syntax is not POSIX and should not be used in sh scripts.`

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