![Linux shell 脚本 - 是否可以捕获命令的输出并在另一个命令中使用它](https://linux22.com/image/574930/Linux%20shell%20%E8%84%9A%E6%9C%AC%20-%20%E6%98%AF%E5%90%A6%E5%8F%AF%E4%BB%A5%E6%8D%95%E8%8E%B7%E5%91%BD%E4%BB%A4%E7%9A%84%E8%BE%93%E5%87%BA%E5%B9%B6%E5%9C%A8%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%91%BD%E4%BB%A4%E4%B8%AD%E4%BD%BF%E7%94%A8%E5%AE%83.png)
因此,我想自动执行将文件上传到 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