Introduction to Unix |
|
![]() |
![]() |
5.3. Accessing VariablesΒΆ
Linux for Programmers and Users, Section 6.3.2
Syntax | Action |
---|---|
$name | Returns the value of name. |
${name} | Use this form when the variable name is
followed by other characters, for example:
filename=${file}.txt |
${name-word} | Returns name if set, and word otherwise. |
${name=word} | Assigns word to name if name is not already set. Returns name. |
${#name} | Returns the length of the value of name. |
${name#pat}
${name##pat}
|
Removes the leading pat from name. The first form removes the smallest matching pattern, the second form removes the largest matching pattern. |
${name%pat}
${name%%pat}
|
Removes the trailing pat from name. The first form removes the smallest matching pattern, the second form removes the largest matching pattern. |
Some Examples:
$ file=foo
$ echo ${file}.txt
foo.txt
$ b=bar
$ echo ${file-$b} --- already set
foo
$ echo ${bob-$b} --- not set
bar
$ echo ${bob=wildcat} --- not set, assignment made
wildcat
$ echo ${bob=jayhawk} --- already set, assignment not made
wildcat
$ echo ${#bob} --- string length
7
$ echo ${bob#wild} --- remove first part
cat
$ echo ${bob%cat} --- remove last part
wild