2017-04-03 28 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

相關問題