如何将此函数作为shell脚本运行?

时间:2018-01-31 06:30:39

标签: bash shell

我正在开发一个shell脚本,我希望在不声明函数的情况下将以下内容作为shell脚本的一部分。基本上,我想在不声明函数的情况下将以下代码转换为shell脚本。

const mapStateToProps = (state, ownProps) => {return {user: state.user}}

进入shell脚本。我做了以下,

#!/bin/bash

function json2keyvalue {
   cat<<EOF | jq -r 'to_entries|map("\(.key)\t\(.value|tostring)")[]'
{
    "hello1": "world1",
    "testk": "testv"
}
EOF
}

while IFS=$'\t' read -r key value
do
    export "$key"="$value"
done < <(json2keyvalue)

但这似乎不起作用。当我运行shell脚本时,它会给出如下错误,其中文件名为values='{"hello1":"world1","hello1.world1.abc1":"hello2.world2.abc2","testk":"testv"}' while IFS=$'\t' read -r key value do export "$key"="$value" done < < (echo $values | jq -r 'to_entries|map("\(.key)\t\(.value|tostring)")[]')

abc.sh

该脚本采用如下的JSON,并将键值转换为环境变量。

./abc.sh: line 6: syntax error near unexpected token `<'
./abc.sh: line 6: `done < < (jq -r 'to_entries|map("\(.key)\t\(.value|tostring)")[]' <<<"$values")'

1 个答案:

答案 0 :(得分:2)

我建议:

#!/bin/bash
shopt -s lastpipe
cat <<EOF | jq -r 'to_entries|map("\(.key)\t\(.value|tostring)")[]' | while IFS=$'\t' read -r key value; do export "$key"="$value"; done
{
    "hello1": "world1",
    "testk": "testv"
}
EOF
  

lastpipe:如果设置,并且作业控制未激活,则shell将运行当前shell环境中未在后台执行的管道的最后一个命令。

<强>更新

如果变量$values包含有效的json代码,则应该有效:

#!/bin/bash
shopt -s lastpipe
values='place valid json code here'
echo "$values" | jq -r 'to_entries|map("\(.key)\t\(.value|tostring)")[]' | while IFS=$'\t' read -r key value; do export "$key"="$value"; done
相关问题