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 called myvar#world
)echo ${myvar#world}
-> shows just Hello
(again, why?)A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.
Variable NamesThe name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _). By convention, Unix shell variables will have their names in UPPERCASE.
Bash Variables Are Untyped. Unlike many other programming languages, Bash does not segregate its variables by "type." Essentially, Bash variables are character strings, but, depending on context, Bash permits arithmetic operations and comparisons on variables.
Valid variable namesVariable names can contain a sequence of alphanumeric characters and underscores. For variables created by you, the user, they should start with either an alphabetical letter or an underscore (i.e. not a number): Valid variable names: hey.
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
.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With