decleareでエラー
decleareでエラー
bashを使って簡単なscriptを書いたときにエラーが出たので軽くメモ
「decleareでエラー」の語感が好きだったという理由です。
#!/bin/bash declare -A arr=( ["aaa"]="100" ["bbb"]="200" ["ccc"]="300" ) for value in ${!arr[@]}; do echo ${value} ${arr[${value}]} done
## 実行 $ ./test.sh ./test.sh: line 2: declare: -A: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...] 0 300
原因はbashのバージョンが低いから
https://stackoverflow.com/questions/6047648/associative-arrays-error-declare-a-invalid-option
/bin/bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin20) Copyright (C) 2007 Free Software Foundation, Inc.
brewでbashをinstallします。4系からdeclareは使用可能です。
$ brew install bash Updating Homebrew... ==> Auto-updated Homebrew! Updated 1 tap (homebrew/core). ==> New Formulae amfora ciphey envoy@1.17 git-xargs kubeconform pythran spectra wasmtime argocd-vault-plugin demumble fcp jrsonnet lexbor ronn sqsmover wxmac@3.0 bosh-cli detect-secrets frum kalker multi-git-status s4cmd svgbob ==> Updated Formulae Updated 1515 formulae. ==> Renamed Formulae weboob -> woob ==> Deleted Formulae libinfinity ==> Downloading https://ghcr.io/v2/homebrew/core/bash/manifests/5.1.8 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/bash/blobs/sha256:62569d2e8452dd3cb61168ffc2581193989503f0e419c3cf1c32984d165ce139 ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:62569d2e8452dd3cb61168ffc2581193989503f0e419c3cf1c32984d165ce139?se=2021-07-07T03%3A40%3A00Z&sig=JwNonIiglsc99nsyES8%2BocmdDokosd8yyg5tVPC4RpU%3D&sp=r&spr=https& ######################################################################## 100.0% ==> Pouring bash--5.1.8.big_sur.bottle.tar.gz 🍺 /usr/local/Cellar/bash/5.1.8: 157 files, 10.9MB ## バージョン確認 $ /usr/local/bin/bash --version GNU bash, バージョン 5.1.8(1)-release (x86_64-apple-darwin20.3.0) Copyright (C) 2020 Free Software Foundation, Inc. ライセンス GPLv3+: GNU GPL バージョン 3 またはそれ以降 <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.
shebanをbrewで入れたbashのpathに変更します。
#!/usr/local/bin/bash ## 実行 $ ./test.sh bbb 200 ccc 300 aaa 100
Macでbash書かないので今更遭遇したエラーでした。書くとしてもサーバで書く。
まぁ書くとしてもzshですよね。