Объявите пустой массив и отличите guish от пустого значения в bash - PullRequest
2 голосов
/ 31 января 2020

Мне нужно проверить, установлены ли определенные переменные среды перед запуском моего скрипта. Я использую технику из этого ответа :

if  [ -z ${var1+x} ]
    echo "var1 not set"
    exit 1
fi

Это хорошо работает для строковых переменных, но есть параметр, который должен быть массивом. Он должен быть установлен, но может быть пустым.

foo=("foo" "bar" "baz")
[ -z ${foo+x} ] # false
bar=()
[ -z ${bar+x} ] # true
[ -z ${baz+x} ] # also true

Итак, мой вопрос, как мне объявить пустой массив, чтобы отличать его от неустановленной переменной. Я также хотел бы проверить, является ли переменная массивом (пустой или нет) или не массивом (установлен или не установлен).

Ответы [ 3 ]

4 голосов
/ 31 января 2020

Вы можете использовать declare -p для определения типа переменной.

scalar=1
declare -p scalar  # declare -- scalar="1"
arr=(1 2 3)
declare -p arr     # declare -a arr=([0]="1" [1]="2" [2]="3")

Необъявленная переменная завершится со значением 1:

unset arr
declare -p arr  # bash: declare: arr: not found
echo $?         # 1

Чтобы проверить, является ли массив пусто, тест ${#arr[@]}.

arr=(1 2 3)
echo ${#arr[@]}  # 3
arr=()
echo ${#arr[@]}  # 0
3 голосов
/ 31 января 2020

Вы можете использовать объявление -p для проверки типа переменной

$ list=()
$ declare -p list
declare -a list='()'

Если вывод содержит "-a", ваш var является массивом, даже если он пуст

1 голос
/ 31 января 2020

Или используйте этот метод

[[ ${var[@]@A} =~ '-a' ]] && echo array || echo variable

На основании этого

$ man bash
...
       ${parameter@operator}
              Parameter transformation.  The expansion is either a transformation of the value of parameter or information about parameter itself, depending
              on the value of operator.  Each operator is a single letter:

              Q      The expansion is a string that is the value of parameter quoted in a format that can be reused as input.
              E      The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'...' quoting mechansim.
              P      The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see PROMPTING below).
              A      The  expansion  is  a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with
                     its attributes and value.
              a      The expansion is a string consisting of flag values representing parameter's attributes.

              If parameter is @ or *, the operation is applied to each positional parameter in turn, and the expansion is the resultant list.  If  parameter
              is  an  array variable subscripted with @ or *, the case modification operation is applied to each member of the array in turn, and the expan‐
              sion is the resultant list.

              The result of the expansion is subject to word splitting and pathname expansion as described below.
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...