2015-09-16 164 views
5

在一段時間讀取線循環中,我看到了這個變量擴展${line/device name:}。我試着用我自己的輸入文件運行腳本,它只是打印出行。Bash變量擴展爲'/'

你能告訴我擴張在做什麼嗎?

+0

這兩個答案都是正確的,但這裏的參數擴展供以後參考和編輯到答案的文檔:http://www.gnu.org/software/bash/manual/html_node/殼參數-Expansion.html –

回答

4

變量名是line。 /用於字符串替換,即「設備名稱:」如果存在任何地方$line被刪除。

> line="a device name: some name" 
> echo ${line/device name:} 
a some name 

您還可以看到#%替代,這代表在line替代的開始和結束。另外要注意的是/替代是一個bash特有的功能(例如ash不支持它,%#看起來很便攜),所以你應該使用#!/bin/bash而不是#!/bin/sh作爲腳本開頭的hashbang。

+0

'%'和''#確實便攜式,作爲[在POSIX殼說明書的一部分(http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 )。 – chepner

+0

謝謝。優秀的答案! – Jimbo

4

它返回$line在卸下子device name:。從bash的手冊頁:

${parameter/pattern/string} 
     Pattern substitution. The pattern is expanded to produce a pattern just as in 
     pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all 
     matches of pattern are replaced with string. Normally only the first match is 
     replaced. If pattern begins with #, it must match at the beginning of the 
     expanded value of parameter. If pattern begins with %, it must match at the 
     end of the expanded value of parameter. If string is null, matches of pattern are deleted and the/following pattern may be omitted. If parameter is @ or 
     *, the substitution operation is applied to each positional parameter in turn, 
     and the expansion is the resultant list. If parameter is an array variable 
     subscripted with @ or *, the substitution operation is applied to each member 
     of the array in turn, and the expansion is the resultant list. 
+0

謝謝。優秀的答案! – Jimbo