bash脚本:获得"除以0和#34;试图声明关联数组

时间:2017-07-25 08:12:03

标签: arrays bash

我有以下(看似)奇怪的问题:我在安装脚本上编写符号链接或复制Wordpress安装的文件,具体取决于它所部署的系统。为了能够遍历要复制的文件列表,我已经声明了一个关联数组。以下代码片段使bash给我一个"除以0"错误:

declare -a files
files["conf/${SYSTEM}/.htaccess"]=".htaccess"
files["conf/${SYSTEM}/wp-config.php"]="wp-config.php"

以下是整个脚本:

#!/usr/bin/env bash

function usage_and_exit {
    echo "Usage: $0 <vm|stage|live> [copy]"
    echo
    echo "Append 'copy' in order to copy files instead of symlinking them."
    echo "    Example: $0 stage copy"
    echo "    take config files from the stage directory and copy them to the"
    echo "    document root."
    exit 1
}

if [ "${PWD##*/}" != "scripts" ]; then
    echo "This script has to be run from inside <DOCUMENT_ROOT>/scripts."
    usage_and_exit
fi

## -------------------------------
##  check command line args
## -------------------------------

if [ $# -eq 0 ]; then
    usage_and_exit
fi

case "$1" in
    vm)
        ;;
    stage)
        ;;
    live)
        ;;
    *)
        echo "Unrecognised argument: $1"
        usage_and_exit
        ;;
esac

COMMAND="ln -s"
if [ $# -eq 2 ]; then
    case "$2" in
        copy)
            COMMAND="cp"
            ;;

        *)
            echo "Unrecognised argument: $2"
            usage_and_exit
            ;;
    esac
fi

## -------------------------------
##  MAIN
## -------------------------------

SYSTEM=$1
cd ..

# array of files to symlink or copy; LHS is source, RHS destination
declare -a files
files["conf/${SYSTEM}/.htaccess"]=".htaccess"
files["conf/${SYSTEM}/wp-config.php"]="wp-config.php"

for file in "${!files[@]}"
do
    # delete destination first if it's a symlink
    if [ -L ${files[$file]} ]; then
        echo "rm: ${files[$file]}"
        rm -f ${files[$file]}
    fi

    echo "${COMMAND}: $file -> ${files[$file]}"
    $COMMAND $file ${files[$file]}
done

有人能指出我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

@ruakh在问题的评论部分提供了正确的提示。它确实是declare -A,而不是declare -a。我尝试一个小“a”的原因是当我第一次尝试使用大写字母时,bash给了我一个错误,所以我认为它必须是我所遵循的操作方法的错字。

最终,罪魁祸首证明是macOS(Sierra)附带的bash过时版本:3.2.57。原因是GPL中bash&gt; = v4的更新条件。 (See this blog post.This answer on AskDifferent为我提供了正确的解决方案。