2015-11-03 39 views

回答

3

bash command substitution syntax already removes trailing newlines。所有你需要做的是重定向到stdout:

$ echo "$(python --version) and more text" 
Python 2.7.8 
and more text 
$ echo "$(python --version 2>&1) and more text" 
Python 2.7.8 and more text 
+0

是的,我的Python版本比你的舊。好傷心...... –

+0

啊,我明白了。我根本沒有捕獲它。沒有值返回,但輸出生成(到標準輸出?),對不對? – orome

+0

並且:'brew install python'。 – orome

3

這裏的事情是,python --version輸出到stderr,而"and more text"到stdout 。

所以,你必須做的唯一的事情就是用2 >&1重定向錯誤輸出到標準輸入:

printf "%s and more text" "$(python --version 2>&1)" 

$ echo "$(python --version 2>&1) and more text" 
Python 2.7.10 and more text 

注意,最初我被輸送至tr -d '\n'using |&

echo "$(python --version |& tr -d '\n') and more text" 
+0

的確不錯,重要的一點是使用'|&'+1 – anubhava

+0

我得到'-bash:命令替換:第1行:語法錯誤附近意外的標記'& ''和'-bash:命令替換:第1行:'python --version |&tr -d'\ n'''。 – orome

+0

@raxacoricofallapatorius你使用的是什麼版本的bash?當它提到它需要Bash 4+時,請參閱鏈接的問題。解決方法是說'python --version 2>&1 | tr -d'\ n''來代替。 – fedorqui