2017-04-03 26 views
3

比方说,我们有这样的一个波纹管bash脚本:如何分离由bash文件生成的每个命令的输出?

echo test 
ls -alh 
pwd 
echo test2 

所以文件可以有任意数量每生产或没有自己的输出就可以了命令。

接着上面的文件运行这样/bin/bash -xe test.sh这将产生以下输出:

+ echo test 
test 
+ ls -alh 
total 32 
drwx------+ 6 daniels staff 204B Apr 3 23:33 . 
drwxr-xr-x+ 64 daniels staff 2.1K Apr 4 01:53 .. 
[email protected] 1 daniels staff 6.0K Apr 3 23:33 .DS_Store 
drwxr-xr-x 5 daniels staff 170B Mar 15 17:03 Todo 
[email protected] 1 daniels staff 282B Apr 3 20:39 test.py 
[email protected] 1 daniels staff 97B Apr 4 01:52 test.sh 
+ pwd 
/Users/daniels/Desktop 
+ echo test2 
test2 

有什么办法来解析生成的输出可靠,并找出如何根据每个命令的输出分开?

对于上面的例子,我们应该能够分离和提取一个基带:

+ echo test 
test 

另一个与

+ ls -alh 
total 32 
drwx------+ 6 daniels staff 204B Apr 3 23:33 . 
drwxr-xr-x+ 64 daniels staff 2.1K Apr 4 01:53 .. 
[email protected] 1 daniels staff 6.0K Apr 3 23:33 .DS_Store 
drwxr-xr-x 5 daniels staff 170B Mar 15 17:03 Todo 
[email protected] 1 daniels staff 282B Apr 3 20:39 test.py 
[email protected] 1 daniels staff 97B Apr 4 01:52 test.sh 

我想解析所述输出的并看看该行是否以+开头,然后将其作为一个命令的开始,但是您可以很容易地得到类似echo + ok的东西,其中wi会使这个逻辑失败。

另一种选择会一直,如果我们可以修改由/bin/bash -x使代替+输出到输出像https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text不过貌似+被硬编码在bash,而不是配置的字符。

任何想法?

回答

7

+是不是硬编码,这是在man bash-x容易描述help set下:

-x  After expanding each simple command, for command, 
      case command, select command, or arithmetic for 
      command, display the expanded value of PS4, fol‐ 
      lowed by the command and its expanded arguments or 
      associated word list. 

而这里的PS4的进一步说明,也man bash

PS4 The value of this parameter is expanded as with PS1 and 
      the value is printed before each command bash displays 
      during an execution trace. The first character of PS4 is 
      replicated multiple times, as necessary, to indicate mul‐ 
      tiple levels of indirection. The default is ``+ ''. 

下面是一个例子:

$ PS4=$'\nAnd now, a word from '; set -x; date; uptime 

And now, a word from date 
Mon Apr 3 16:20:35 PDT 2017 

And now, a word from uptime 
16:20:35 up 65 days, 1:24, 6 users, load average: 1.20, 1.42, 1.37 

您可以使用它嵌入特殊标记或字符,只要您认为合适。

+0

嗯,我发现这个http://stackoverflow.com/questions/12048296/how-to-have-customize-log-format-for-set-x-in-bash-shell-script,并感到困惑。使用'PS4 ='测试并且完美地工作。谢谢。 – daniels

相关问题