Fish
fish shell:通過管道或讀取將多行輸出擷取到變數
如果你
curl https://www.toptal.com/developers/gitignore/api/python
您按預期看到文件,帶有換行符。但如果我
set response (curl https://www.toptal.com/developers/gitignore/api/python) echo $response
在魚中,換行符消失了。我看過魚
read
,但是url $gitignoreurlbase/python | read response # I have also tried read -d 'blah' echo $response
只是顯示一個空白。
如何擷取多行輸出?
替換
set var (command)
為set var (command | string split0)
解釋:
預設情況下,命令替換在換行符上拆分。$response 變數是輸出的行列表。這是記錄在案的
$ set var (seq 10) $ set --show var $var: not set in local scope $var: set in global scope, unexported, with 10 elements $var[1]: length=1 value=|1| $var[2]: length=1 value=|2| $var[3]: length=1 value=|3| $var[4]: length=1 value=|4| $var[5]: length=1 value=|5| $var[6]: length=1 value=|6| $var[7]: length=1 value=|7| $var[8]: length=1 value=|8| $var[9]: length=1 value=|9| $var[10]: length=2 value=|10| $var: not set in universal scope
幸運的是,補救措施也是如此
$ set var (seq 10 | string split0) $ set -S var $var: not set in local scope $var: set in global scope, unexported, with 1 elements $var[1]: length=21 value=|1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n| $var: not set in universal scope # OR $ set oldIFS $IFS $ set --erase IFS $ set var (seq 10) $ set -S var $var: not set in local scope $var: set in global scope, unexported, with 1 elements $var[1]: length=20 value=|1\n2\n3\n4\n5\n6\n7\n8\n9\n10| $var: not set in universal scope $ set IFS $oldIFS
請注意與
string split0
保留尾隨換行符的區別。如果您可以將 $response 作為行列表,但您只想正確顯示它:
printf "%s\n" $response # or, with just a literal newline as the join string string join " " $respose