2015-11-02 27 views
1

我的腳本:爲什麼讀命令讀取所有字爲頭名

#!/bin/bash 

IFS=',' 

read a b c d e f g <<< $(echo "1,2,3,4,5,6,7") # <- this could be any other commands, I am just making up a dummy command call 

echo $a 
echo $b 
echo $c 

我,它預計到輸出

1 
2 
3 

而是將其輸出:

1 2 3 4 5 6 7 
blank line 
blank line 

我做了什麼錯誤?

+0

https://www.gnu.org/軟件/ bash/manual/bash.html#Word-Splitting – 4ae1e1

+0

[Linux bash:多變量賦值]的可能重複(http://stackoverflow.com/questions/1952404/linux-bash-multiple-variable-assignment) – itwasntme

+0

你只需要引用子命令「$()」'並且它會按照你的預期工作,否則'''會過早地被擴展。 – 123

回答

3

你應該使用這樣的:

IFS=, read a b c d e f g <<< "1,2,3,4,5,6,7" 

使用IFS在同一行read,以避免弄亂當前shell環境。

並避免使用命令替換只是爲了捕獲單個echo命令的輸出。

如果你想在read使用命令的輸出則更好bash使用process substitution

IFS=, read a b c d e f g < <(echo "1,2,3,4,5,6,7") 
+1

謝謝!像魅力一樣工作! –

+0

嗨anubhava,你能解釋一下「<(command)」的含義嗎?用谷歌搜索它,但沒有發現有用的東西。特別是爲什麼兩個「<」之間有空格? –

+0

這就是所謂的*過程替代*。只是谷歌,我在手機上,否則我可以給你一個直接的鏈接。 – anubhava

1

這工作:

#!/bin/bash 
IFS=',' 
read a b c d e f g <<< "$(echo "1,2,3,4,5,6,7")" 
echo $a; echo $b; echo $c 

注意報價:"$(...)"。沒有它,字符串分割,成爲

$(echo "1,2,3,4,5,6,7")  ===> 1 2 3 4 5 6 7 

給予1 2 3 4 5 6 7讀不產生分裂,因爲IFS是,

當然,這也適用(IFS僅適用於執行命令:讀):

#!/bin/bash 
IFS=',' read a b c d e f g <<< "$(echo "1,2,3,4,5,6,7")" 
echo $a; echo $b; echo $c 

而且是連這樣的好:

#!/bin/bash 
IFS=',' read a b c d e f g <<< "1,2,3,4,5,6,7" 
echo $a; echo $b; echo $c 

你並不需要「執行回聲「來獲得一個變量,你已經擁有了它。

1

從技術上講,您的代碼是正確的。在bash 4.3及更早的版本中,在字符串處理中存在一個錯誤,它將錯誤地將單詞拆分應用於命令替換的未引用擴展。下面將解決的bug:

# Quote the expansion to prevent bash from splitting the expansion 
# to 1 2 3 4 5 6 7 
$ read a b c d e f g <<< "$(echo "1,2,3,4,5,6,7")" 

和會

# A regular string is not split 
$ read a b c d e f g <<< 1,2,3,4,5,6,7 

bash 4.4,這似乎是固定的:

$ echo $BASH_VERSION 
4.4.0(1)-beta 
$ IFS=, 
$ read a b c d e f g <<< $(echo "1,2,3,4,5,6,7") 
$ echo $a 
1 
+0

我剛剛檢查了我的bash,正如你所說的,我的是bash 4.3,猜測這解釋了爲什麼lol –

+0

Bash 4.4還沒有被釋放,不幸的是,所以現在的解決方法是唯一的實際解決方案,除非你想從Git存儲庫並運行測試版軟件。 – chepner

相關問題