Linux shell 脚本 - 是否可以捕获命令的输出并在另一个命令中使用它

Linux shell 脚本 - 是否可以捕获命令的输出并在另一个命令中使用它

因此,我想自动执行将文件上传到 Rackspace 的过程。以下是我需要执行的操作:

首先,我输入:

 curl -D - \
        -H "X-Auth-Key: 123456789abcdefghijk" \
        -H "X-Auth-User: MyUsername" \
        https://auth.api.rackspacecloud.com/v1.0

这给了我如下的回应:

HTTP/1.1 204 No Content
Server: Apache/2.2.3 (Red Hat)
vary: X-Auth-Token,X-Auth-Key,X-Storage-User,X-Storage-Pass
X-Storage-Url: https://storage101.ord1.clouddrive.com/v1/BlahBlah
Cache-Control: s-maxage=46818
Content-Type: text/xml
Date: Tue, 07 Feb 2012 05:07:09 GMT
X-Auth-Token: SOME_AUTH_TOKEN_I_NEED
X-Storage-Token: blahblah
X-Server-Management-Url: https://servers.api.rackspacecloud.com/v1.0/123456
Connection: Keep-Alive
X-CDN-Management-Url: https://cdn2.clouddrive.com/v1/BlahBlah

接下来我需要上传一个文件:

curl -X PUT -T foo.txt -D - \
     -H "ETag: 7849eb8d56581fa7c4896bb0db64892c" \
     -H "Content-Type: text/plain" \
     -H "X-Auth-Token: SOME_AUTH_TOKEN_I_NEED" \
     -H "X-Object-Meta-Screenie: Test" \
     https://storage101.ord1.clouddrive.com/v1/BlahBlah/MyBackup/foo.txt

所以基本上,我需要解析身份验证令牌(X-Auth-Token)以及存储 URL(X-Storage-Url)并动态构建下一个命令。

有没有办法用 shell 脚本来做到这一点,比如使用正则表达式之类的?任何指点都将不胜感激!

答案1

肯定有比这更优雅的解决方案,但我的脑海中浮现出一种快速而肮脏的 bash 实现方式,如下所示:

#!/bin/bash

xauthtoken=`curl -D - \
        -H "X-Auth-Key: 123456789abcdefghijk" \
        -H "X-Auth-User: MyUsername" \
        https://auth.api.rackspacecloud.com/v1.0 | grep X\-Auth\-Token | awk '{print $2}'`

xstorageurl=`curl -D - \
        -H "X-Auth-Key: 123456789abcdefghijk" \
        -H "X-Auth-User: MyUsername" \
        https://auth.api.rackspacecloud.com/v1.0 | grep X\-Storage\-Url | awk '{print $2}'`

curl -X PUT -T foo.txt -D - \
     -H "ETag: 7849eb8d56581fa7c4896bb0db64892c" \
     -H "Content-Type: text/plain" \
     -H "X-Auth-Token: ${xauthtoken}" \
     -H "X-Object-Meta-Screenie: Test" \
     $xstorageurl

相关内容