yab*_*yab 9 bash optimization curl sed
我正在尝试优化我的代码,并借用了一段特定的代码.我想删除sed所以我没有在主循环中使用任何外部进程.
function sendMsg () {
value=$(echo $1 | sed 's/ /%20/g;s/!/%21/g;s/"/%22/g;s/#/%23/g;s/\&/%26/g;s/'\''/%28/g;s/(/%28/g;s/)/%29/g;s/:/%3A/g;s/\//%2F/g');
str="http://www.xxxx.com/api.ashx?v=1&k=$Key&a=send&w=$value";
curl -s $str;
}
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,我编辑了这个.$ value只是通过函数末尾的curl命令转换为适当的url输出.
虽然这很好用,但我最感兴趣的是尽可能快地处理它,如果可以的话,不要求外部进程.
感谢您的评论到目前为止!
我到目前为止是这样的:
function sendMsg () {
str="http://www.xxxx.com/api.ashx?v=1&k=$Key&a=send&w=";
curl -s $str --data-urlencode "$1";
}
Run Code Online (Sandbox Code Playgroud)
我至少在正确的轨道上吗?
首先,您的问题的答案:如果您正在进行单一替换或过滤,使用模式匹配会更快:
$ foo=${bar/old/new} # Faster
$ foo=$(sed 's/old/new/' <<<$bar # Slower
Run Code Online (Sandbox Code Playgroud)
第一个不需要产生一个子shell,然后运行sed
,然后将其替换回来$foo
.但是,如果你这样做了近十几次,我相信使用sed
可能会更快:
value=$(sed -e 's/ /%20/g' \
-e 's/!/%21/g' \
-e 's/"/%22/g' \
-e 's/#/%23/g' \
-e 's/\&/%26/g' \
-e 's/'\''/%28/g' \
-e 's/(/%28/g' \
-e 's/)/%29/g' \
-e 's/:/%3A/g' \
-e 's/\//%2F/g'<<<$1);
Run Code Online (Sandbox Code Playgroud)
请注意,由于每个替换命令都在其自己的行上,因此该语法更易于阅读.另请注意,<<<
无需回声和管道.
这只能进行一次调用,sed
而模式匹配必须多次完成.
但是,您应该使用--data
而--data-uuencode
不是自己构建查询字符串:
$ curl -s http://www.xxxx.com/api.ashx \
--data v=1 \
--data k=$Key \
--data a=send \
--data-urlencode w="$value";
Run Code Online (Sandbox Code Playgroud)
在--data--urlencode
将编码的价值$value
给你,所以你不必这样做.不幸的是,这个参数在所有版本中都不存在curl
.它在2008年1月的版本7.18.0中添加.运行curl --version
以查看您拥有的版本:
$ curl --version # Life is good
curl 7.30.0 (x86_64-apple-darwin13.0) libcurl/7.30.0 SecureTransport zlib/1.2.5
$ curl --version # David Sad
curl 7.15.5 (x86_64-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
Run Code Online (Sandbox Code Playgroud)
尝试这个我得到一个'不支持的API版本ERROR',即使我的卷曲 - 版本报告7.29.0
我无法测试你有什么,但我决定尝试我们的Jenkins服务器,看看我是否可以设置构建描述.我确保描述中有空格,所以它需要--data-urlencoding
.这个命令有效:
$ curl --user dweintraub:swordfish \
--data Submit=Submit \
--data-urlencode description="This is my test descripition" \
http://jenkins.corpwad.com/jenkins/job/Admin-5.1.1/138/submitDescription
Run Code Online (Sandbox Code Playgroud)
这就像我做的那样:
$ curl -user "dweintraub:swordfish http://jenkins.corpwad.com/jenkins/job/Admin-5.1.1/138/submitDescription?Submit=Submit&desciption=This%20is%20my%20test%20descripition"
Run Code Online (Sandbox Code Playgroud)
请注意,--data
为您添加问号.
(不,swordfish
不是我的密码).
它并不像你的命令那么复杂,但它可能有助于指出你遇到问题的地方.你有用户名和密码吗?如果是这样,您需要--user
参数.