tags:

views:

56

answers:

2

Given:

myvar=Hello
  • echo $myvar -> Shows Hello (fine so far)
  • echo $myvar#world -> shows Hello#world (why?? I thought it would complain that here is no such variable calld myvar#world
  • echo ${myvar#world} -> shows just Hello (again, why??)

Thanks in advance

+5  A: 

variables cannot contain a "#" so the shell knows its not part of a variable.

The construct ${myvar#world} actually is a string manipulator explained below:

# is actuially a string modifier that will remove the first part of the string matching "world". Since there is no string matching world in myvar is just echos back "hello"

ennuikiller
+3  A: 

The second case splits up into three parts:

[echo] [$myvar][#world]
 1      2       3

Part 1 is the command, part 2 is a parameter, and part 3 is a string literal. The parameter stops on r since the # can't be part of the variable name (#'s are not allowed in variable names.)

The shell parser will recognise the start of a parameter name by the $, and the end by any character which cannot be part of the variable name. Normally only letters, numbers and underscores are allowed in a variable name, anything else will tell the shell that you're finished specifying the name of the variable.

All of these will print out $myvar followed by six literal characters:

echo $myvar world
echo $myvar?world
echo $myvar#world

If you want to put characters which can be part of a parameter directly after the parameter, you can include braces around the parameter name, like this:

myvar=hello
echo ${myvar}world

which prints out:

helloworld

Your third case is substring removal, except without a match. To get it to do something interesting, try this instead:

myvar="Hello World"
echo ${myvar#Hello }

which just prints World.

Douglas
I got the second part, in the first case though, it is still printing out the #, so the output is Hello#world instead of Hello world
sunny8107
Does the edit make it clearer?
Douglas