Bash未绑定变量数组(脚本:s3-bash)

问题描述 投票:4回答:4

我正在使用:s3-bash,当我在我的本地环境中运行它(OS X 10.10.1)我没有任何问题,当我尝试在ubuntu server 14.04.1上运行它时出现以下错误:

./s3-common-functions: line 66: temporaryFiles: unbound variable
./s3-common-functions: line 85: temporaryFiles: unbound variable

我查看了s3-common-functions脚本,变量看起来正确初始化(作为数组):

# Globals
declare -a temporaryFiles

但是评论中有一个注释,我确定它是否相关:

# Do not use this from directly. Due to a bug in bash, array assignments do not work when the function is used with command substitution
function createTemporaryFile
{
    local temporaryFile="$(mktemp "$temporaryDirectory/$$.$1.XXXXXXXX")" || printErrorHelpAndExit "Environment Error: Could not create a temporary file. Please check you /tmp folder permissions allow files and folders to be created and disc space." $invalidEnvironmentExitCode
    local length="${#temporaryFiles[@]}"
    temporaryFiles[$length]="$temporaryFile"
}
bash
4个回答
9
投票

这里似乎有一个bash行为改变。

由kojiro发现:CHANGES

HHHH。修复了导致`declare'和`test'查找已赋予属性但未赋值的变量的错误。这些变量没有设定。

$ bash --version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
$ set -u
$ declare -a tF
$ echo "${#tF[@]}"
0

$ bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ set -u
$ declare -a tF
$ echo "${#tF[@]}"
0

$ bash --version
GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ set -u
$ declare -a tF
$ echo "${#tF[@]}"
-bash: tF: unbound variable

你可以在较新的bash版本上使用declare -a tF=()来解决这个问题。

$ declare -a tF=()
$ echo "${#tF[@]}"
0

3
投票

Bash可以使用短划线将空值替换为未设置的变量。

set -u
my_array=()
printf "${my_array[@]-}\n"

此特定示例将不会打印任何内容,但它也不会为您提供未绑定的变量错误。

Stolen from here


0
投票

更改了temporaryfiles的数组声明

declare -a temporaryFiles

至:

temporaryFiles=()

为什么这在ubuntu 14.04.1 Linux 3.13.0-32-generic x86_64OS X不同/无功能我不确定?


0
投票
find $fullfolder -type f |
while read fullfile
do
    filename=$(basename "$fullfile")
    ext=$([[ $filename = *.* ]] && printf %s ${filename##*.} || printf 'NONE')
    arr+=($ext)
    echo ${#arr[@]}
done
echo ${#arr[@]}

为什么for循环中的$ {#arr [@]}产生正确的结果,但外部的那个给出0?

© www.soinside.com 2019 - 2024. All rights reserved.