Variable Substitutionby Pigbrain

Variable Substitution

  • 아래 표현식들에는 공백(space)를 포함해선 안된다
  • 콜론(:)은 옵션으로 쓰이며 만약 콜론이 있을 경우 값은 null이 나오지 않는다
FormMeaning
var=value Set each variable var to a value
${var} Use value of var
${var:-value} Use var if set; otherwise, use value
${var:=value} Use var if set; otherwise, use value and assign value to var
${var:=value} Use var if set; otherwise, use value and assign value to var
${#var} Use the length of var
${#*} Use the number of positional parameters
${#@} Use the number of positional parameters
${var:pos} Starting at position pos (0-based) in variable
${var:pos:len} var, extract len characters, or extract rest of string
${var/pat/repl} Use value of var, with first match of pat replaced with repl
${var/pat} Use value of var, with first match of pat deleted
${var/pat/repl} Use value of var, with first match of pat replaced with repl

Example

prompt> var1=apple var2=banana
prompt> echo ${var1} ${var2}
apple banana

prompt> echo ${var1:-none} ${var3:-none}
apple none

prompt> echo ${var3}
  
prompt> echo ${var3:=computer}
computer  
prompt> echo ${var3}
computer  

prompt> echo ${#var3}
8  

prompt> cat test.sh
echo ${#*}
echo ${#@}
prompt> ./test.sh a b c d 
4
4

prompt> echo ${var3:3}
puter
prompt> echo ${var3:3:2}
pu

prompt> echo ${var3/com/moc}
mocputer
prompt> echo ${var3/com}
puter

prompt> var4=apple1apple2apple3
prompt> echo ${var4/apple/banana}
banana1apple2apple3
prompt> echo ${var4//apple/banana}
banana1banana2banana3


참고

Published 18 March 2016