简体   繁体   English

如何取消 bash 中的数组?

[英]How to unset array in bash?

In bash shell for variables:在 bash shell 为变量:

#!/bin/bash
set -o nounset

my_var=aaa
unset var
echo "$var"

Because set command is defined to return error if variable is not set, last line returns error:因为set命令被定义为在未设置变量时返回错误,所以最后一行返回错误:

line 6: var: unbound variable第 6 行:var:未绑定变量

OK, that is what I want.好的,这就是我想要的。

Now the same thing with arrays:现在与 arrays 相同:

#!/bin/bash
set -o nounset

my_array=(aaa bbb)
unset my_array
echo "${my_array[@]}"

But to my surprise last line does not return error.但令我惊讶的是,最后一行没有返回错误。 I would like bash script to return error when array is not defined.我希望 bash 脚本在未定义数组时返回错误。

${my_array[@]} is similar to $@ which is documented to be ignored by nounset : ${my_array[@]}类似于$@ ,它被记录为被nounset忽略:

-u Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion. -u在执行参数扩展时,将除特殊参数“@”和“*”之外的未设置变量和参数视为错误。 If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status.如果尝试对未设置的变量或参数进行扩展,则 shell 会打印一条错误消息,如果不是交互式的,则以非零状态退出。

Returning the array size is not ignored, though.但是,返回数组大小不会被忽略。 Prepend the following line to make sure the array is not unset:在前面添加以下行以确保数组未被取消设置:

: ${#my_array[@]}

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

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