首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取shell命令的准确输出

问获取shell命令的准确输出
EN

Stack Overflow用户
提问于 2016-10-05 03:12:25
回答 2查看 266关注 0票数 1

bash手册上写着关于命令替换

Bash通过执行命令并将命令替换为命令的标准输出来执行扩展,并删除所有尾随的换行符。

演示-3个字符,换行符第一:

代码语言:javascript
复制
$ output="$(printf "\n\nx")"; echo -n "$output" | wc -c
3

在这里,换行符不在末尾,也不被移除,所以计数是3。

演示-3个字符,换行符最后:

代码语言:javascript
复制
$ output="$(printf "x\n\n")"; echo -n "$output" | wc -c
1

这里,从末尾移除换行符,所以计数是1。

TL;DR

什么是健壮的工作来将命令的二进制干净输出输入到变量中?

伯恩外壳兼容性加分。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-05 05:55:32

以"Bourne兼容“的方式进行此操作的唯一方法是使用外部实用程序。

除了在c ++中写一个,您还可以使用xxd和expr (例如):

代码语言:javascript
复制
$ output="$(printf "x\n\n"; printf "X")"         # get the output ending in "X".
$ printf '%s' "${output}" | xxd -p               # transform the string to hex.
780a0a58
$ hexstr="$(printf '%s' "${output}" | xxd -p)"   # capture the hex
$ expr "$hexstr" : '\(.*\)..'                    # remove the last two hex ("X").
780a0a
$ hexstr="$(expr "$hexstr" : '\(.*\)..')         # capture the shorter str.
$ printf "$hexstr" | xxd -p -r | wc -c           # convert back to binary.
3

缩短:

代码语言:javascript
复制
$ output="$(printf "x\n\n"; printf "X")"
$ hexstr="$(printf '%s' "${output}" | xxd -p )"
$ expr "$hexstr" : '\(.*\)..' | xxd -p -r | wc -c
3

命令xxd用于将其转换为二进制文件的能力。

请注意,对于许多UNICODE字符(多字节字符),wc将失败:

代码语言:javascript
复制
$ printf "Voilà" | wc -c
6

$ printf "★" | wc -c
3

它将打印字节数,而不是字符。

变量${#var}的长度在旧的shell中也会失败。

当然,要使它在Bourne中运行,必须使用`…`而不是$(…)。

票数 2
EN

Stack Overflow用户

发布于 2016-10-05 03:12:25

在bash中,可以使用${parameter%word}形式的壳参数展开:

$ output="$(printf“x\n\n;echo X)";echo -n "${output%X}”{output%X}“\ wc -c 3

这也是由POSIX.1-2008指定的替换。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39864848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档