Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 从shell命令的响应中获取文本_Bash_Shell_Zsh - Fatal编程技术网

Bash 从shell命令的响应中获取文本

Bash 从shell命令的响应中获取文本,bash,shell,zsh,Bash,Shell,Zsh,我想写一个脚本来自动化我所做的重复性任务 我发出以下命令: heroku pgbackups:capture --expire 我得到了这样的回应 我的数据库URL(数据库URL)--备份--->b677 然后,我用捕获号(上面的b677)发出这个命令 如何解析文本并将值放入下一个命令?只需解析第一个命令的输出并将其保存到变量中即可: capnum=$(heroku pgbackups:capture --expire | grep -- "--->" | awk '{print $NF

我想写一个脚本来自动化我所做的重复性任务

我发出以下命令:

heroku pgbackups:capture --expire
我得到了这样的回应

我的数据库URL(数据库URL)--备份--->b677

然后,我用捕获号(上面的b677)发出这个命令


如何解析文本并将值放入下一个命令?

只需解析第一个命令的输出并将其保存到变量中即可:

capnum=$(heroku pgbackups:capture --expire | grep -- "--->" | awk '{print $NF}')
然后执行,

curl -o latest.dump $(heroku pgbackups:url ${capnum})
或者,你可以说:

curl -o latest.dump $(heroku pgbackups:url $(heroku pgbackups:capture --expire | grep -- "--->" | awk '{print $NF}'))

如果捕获号码的格式总是相同的,您可以使用

captureNumber=`heroku pgbackups:capture --expire | grep -o [a-Z][0-9]*$`

curl -o latest.dump `heroku pgbackups:url ${captureNumber}`
或者,更一般地说,检测最后一个空格并使用行的剩余部分:

captureNumber=`heroku pgbackups:capture --expire | grep -o \s.*$`

如果有我不知道的不同格式,请调整正则表达式;如果正则表达式没有很好地捕获格式,请使用devnull的答案

使用sed和shell脚本是可行的

#!/bin/sh
s=`heroku pgbackups:capture --expire`
id=`echo ${s} | sed -e "s/^.*> \(b[0-9]*\)$/\1/"`
url=`echo heroku pgbackups:url ${id}`
curl -o last.dump "${url}"
这不是最漂亮的shell脚本,但它可以作为概念的证明

更多方法:

read __ __ __ URL < <(exec heroku pgbackups:capture --expire)
curl -o latest.dump "$URL"

curl -o latest.dump $(exec heroku pgbackups:capture --expire | cut -f 4 -d ' ')

curl -o latest.dump $(exec heroku pgbackups:capture --expire | sed 's|.* ||')

read______;URL<您的意思是自动执行此过程,而无需记住并键入捕获编号?
read __ __ __ URL < <(exec heroku pgbackups:capture --expire)
curl -o latest.dump "$URL"

curl -o latest.dump $(exec heroku pgbackups:capture --expire | cut -f 4 -d ' ')

curl -o latest.dump $(exec heroku pgbackups:capture --expire | sed 's|.* ||')