如何使用 echo 命令在下一行打印变量值

如何使用 echo 命令在下一行打印变量值

我收到如下 curl 命令输出

curl -s https://api.github.com/repos/harshavardhanc/dockerfile-ansible/pulls\?state\=all | jq -r '.[]|(.number|tostring)+" "+.user.login+" "+.created_at+" "+.merged_at'
5 test 2019-09-27T11:06:23Z 2019-09-27T11:09:28Z
4 test1 2019-09-26T16:56:40Z 2019-09-26T16:57:02Z
3 test2 2019-09-26T16:54:25Z 2019-09-26T16:54:55Z
2 test3 2019-09-26T16:52:59Z 2019-09-26T16:55:19Z
1 test4 2019-09-26T16:46:52Z 2019-09-26T16:47:25Z

我将其存储在一个变量中,并尝试通过 echo 变量将值传递给另一个命令来解析输出。但是当我尝试 echo 变量时,它会将所有行打印为一行。

prlist=$(curl -s https://api.github.com/repos/harshavardhanc/dockerfile-ansible/pulls\?state\=all | jq -r '.[]|(.number|tostring)+" "+.user.login+" "+.created_at+" "+.merged_at')
echo $prlist
5 test 2019-09-27T11:06:23Z 2019-09-27T11:09:28Z 4 test1 2019-09-26T16:56:40Z 2019-09-26T16:57:02Z 3 test2 2019-09-26T16:54:25Z 2019-09-26T16:54:55Z 2 test3 2019-09-26T16:52:59Z 2019-09-26T16:55:19Z1 test4 2019-09-26T16:46:52Z 2019-09-26T16:47:25Z

如何避免在不同的行中打印?请帮忙。

答案1

echo您所描述的是未加引号的变量的标准行为:

$ prlist=$(curl -s https://api.github.com/repos/harshavardhanc/dockerfile-ansible/pulls\?state\=all | 
           jq -r '.[]|(.number|tostring)+" "+.user.login+" "+.created_at+" "+.merged_at')
$ echo $prlist
5 SMYALTAMASH 2019-09-27T11:06:23Z 2019-09-27T11:09:28Z 4 ganesh-28 2019-09-26T16:56:40Z 2019-09-26T16:57:02Z 3 ganesh-28 2019-09-26T16:54:25Z 2019-09-26T16:54:55Z 2 ganesh-28 2019-09-26T16:52:59Z 2019-09-26T16:55:19Z 1 ganesh-28 2019-09-26T16:46:52Z 2019-09-26T16:47:25Z

这是因为$prlist没有引用。比较一下如果引用它会发生什么:

$ echo "$prlist"
5 SMYALTAMASH 2019-09-27T11:06:23Z 2019-09-27T11:09:28Z
4 ganesh-28 2019-09-26T16:56:40Z 2019-09-26T16:57:02Z
3 ganesh-28 2019-09-26T16:54:25Z 2019-09-26T16:54:55Z
2 ganesh-28 2019-09-26T16:52:59Z 2019-09-26T16:55:19Z
1 ganesh-28 2019-09-26T16:46:52Z 2019-09-26T16:47:25Z

但为什么要使用变量呢?您可以直接解析输出curl

curl ... | jq ... | someOtherCommand

像这样:

curl -s https://api.github.com/repos/harshavardhanc/dockerfile-ansible/pulls\?state\=all | 
  jq -r '.[]|(.number|tostring)+" \
    "+.user.login+" "+.created_at+" "+.merged_at'curl \
    -s https://api.github.com/repos/harshavardhanc/dockerfile-ansible/pulls\?state\=all |
 someOtherCommand

相关内容