随着答案的改进
https://dev59.com/q18d5IYBdhLWcg3wcx5V#26809278
脚本生成几种格式,可以在包含时使用。脚本符合BASH规范,并经过shellcheck检查。
#!/bin/bash
X=("hello world" "goodnight moon" 'say "boo"' 'foo\bar')
return_array() {
rf="${return_format}"
if [[ $rf = "php5" ]]; then
q=("<?php return array(" ");")
elif [[ $rf = "php" ]];then
q=("<?php return [" "];")
elif [[ $rf = "json" ]];then
q=("{" "}")
else
q=("[" "]")
fi
echo -n "${q[0]}"
while [[ $# -gt 0 ]]; do
x=${1//\\/\\\\}
echo -n "\"${x//\"/\\\"}\""
[[ $# -gt 1 ]] && echo -n ', '
shift
done
echo "${q[1]}"
}
echo "PHP 5.x"
return_format="php5"
return_array "${X[@]}"
echo "PHP 7.x"
return_format="php"
return_array "${X[@]}"
echo "JSON for PHP"
return_format="json"
return_array "${X[@]}"
echo "JSON for JS"
return_format=
return_array "${X[@]}"
将会产生输出:
PHP 5.x
<?php return array("hello world", "goodnight moon", "say \"boo\"", "foo\\bar");
PHP 7.x
<?php return ["hello world", "goodnight moon", "say \"boo\"", "foo\\bar"];
JSON for PHP
{"hello world", "goodnight moon", "say \"boo\"", "foo\\bar"}
JSON for JS
["hello world", "goodnight moon", "say \"boo\"", "foo\\bar"]
for f in "${X[@]}"; do printf '%s' "$f" | jq -R -s .; done | jq -s .
- that other guy[ "" ]
。 - Jan GassenX
未声明为数组时才会发生这种情况。 - thm