我怎样才能将此功能作为shell脚本运行? [英] How can I run this function as a shell script?

查看:69
本文介绍了我怎样才能将此功能作为shell脚本运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理shell脚本,并且希望在不声明函数的情况下作为shell脚本的一部分执行以下操作.基本上,我想将以下代码简单地转换为shell脚本,而无需声明函数.

I am working on a shell script, and I wish to do the following as part of a shell script without declaring a function. Basically, I would like to convert the following code into a shell script simply without declaring a function.

#!/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脚本.我做了以下,

into a shell script. I did the following,

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)")[]')

但这似乎不起作用.当我运行shell脚本时,它给出如下错误,其中文件名为 abc.sh .

But this doesn't seem to work. When I run the shell script, it gives the error as follows, where file name is abc.sh.

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

该脚本采用类似于以下内容的JSON,并将键值转换为环境变量.

The script takes a JSON like the following, and converts the key-values into environment variables.

{
    "hello1": "world1",
    "testk": "testv"
}

推荐答案

我建议:

#!/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 :如果设置了该选项,并且作业控制未处于活动状态,则外壳程序会在当前外壳程序环境中运行不在后台执行的管道的最后一条命令.

lastpipe: If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.

更新:

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

If variable $values contains valid json code, this should work:

#!/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

这篇关于我怎样才能将此功能作为shell脚本运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆