Bash Is Reading Varible as a Command and Not a String

RSS Feed Share on Twitter

Purchase this Trounce Scripting Tutorial equally a PDF for simply $5

iv. Variables - Part I

Just well-nigh every programming language in being has the concept of variables - a symbolic name for a clamper of memory to which we can assign values, read and manipulate its contents. The Bourne crush is no exception, and this section introduces that thought. This is taken farther in Variables - Role 2 which looks into variables which are prepare for us by the environment.
Let's await back at our first Hello World example. This could exist done using variables (though it'southward such a simple example that it doesn't really warrant it!)
Note that there must be no spaces effectually the "=" sign: VAR=value works; VAR = value doesn't piece of work. In the starting time case, the shell sees the "=" symbol and treats the command as a variable assignment. In the second example, the trounce assumes that VAR must be the proper noun of a command and tries to execute information technology.
If yous think about it, this makes sense - how else could y'all tell information technology to run the command VAR with its first argument being "=" and its 2nd argument being "value"?
Enter the following code into var.sh:


var.sh

          #!/bin/sh                      
MY_MESSAGE
= "Hello World"
echo $MY_MESSAGE

This assigns the cord "How-do-you-do World" to the variable MY_MESSAGE then echoes out the value of the variable.
Notation that we need the quotes around the string How-do-you-do World. Whereas nosotros could become abroad with repeat Howdy World because echo will take whatever number of parameters, a variable tin can merely hold i value, so a cord with spaces must be quoted so that the beat out knows to care for it all as one. Otherwise, the crush will try to execute the command Earth later on assigning MY_MESSAGE=Hello

The shell does not care about types of variables; they may store strings, integers, real numbers - anything you like.
People used to Perl may be quite happy with this; if you've grown up with C, Pascal, or worse notwithstanding Ada, this may seem quite strange.
In truth, these are all stored every bit strings, but routines which expect a number can treat them equally such.
If y'all assign a string to a variable then try to add ane to it, you will not get abroad with information technology:

          $ x          =          "hello"                      
$ expr $x + 1
expr : not - numeric statement
$

This is because the external program expr only expects numbers. But there is no syntactic departure betwixt:

          MY_MESSAGE          =          "Hi World"                      
MY_SHORT_MESSAGE
= hello
MY_NUMBER
= 1
MY_PI
= three.142
MY_OTHER_PI
= "3.142"
MY_MIXED
= 123abc

Notation though that special characters must be properly escaped to avoid interpretation past the vanquish.
This is discussed further in Chapter 6, Escape Characters.

We can interactively fix variable names using the read command; the following script asks you for your name then greets you lot personally:


var2.sh

          #!/bin/sh                      
echo What is your name ?
read MY_NAME
echo "How-do-you-do $MY_NAME - hope you're well."

Mario Bacinsky kindly pointed out to me that I had originally missed out the double-quotes in line 3, which meant that the unmarried-quote in the word "you're" was unmatched, causing an error. Information technology is this kind of thing which tin can drive a beat programmer crazy, so sentry out for them!

This is using the shell-builtin command read which reads a line from standard input into the variable supplied.
Note that even if you give it your full name and don't use double quotes effectually the repeat command, it still outputs correctly. How is this washed? With the MY_MESSAGE variable earlier we had to put double quotes around information technology to set information technology.
What happens, is that the read command automatically places quotes effectually its input, so that spaces are treated correctly. (You volition demand to quote the output, of course - east.g. echo "$MY_MESSAGE").

Scope of Variables

Variables in the Bourne shell do non have to exist declared, as they do in languages similar C. But if you effort to read an undeclared variable, the result is the empty string. You get no warnings or errors. This tin can cause some subtle bugs - if you assign
MY_OBFUSCATED_VARIABLE=Hello
and then
echo $MY_OSFUCATED_VARIABLE
Then you will get nothing (as the second OBFUSCATED is mis-spelled).

There is a command called export which has a key consequence on the scope of variables. In order to really know what's going on with your variables, you will need to understand something nigh how this is used.

Create a pocket-sized trounce script, myvar2.sh:


myvar2.sh

          #!/bin/sh                      
echo "MYVAR is: $MYVAR"
MYVAR
= "hi there"
echo "MYVAR is: $MYVAR"

Now run the script:

          $                    ./          myvar2          .          sh
MYVAR is
:
MYVAR is
: hi at that place

MYVAR hasn't been set to any value, then it'south blank. Then we give it a value, and it has the expected result.
At present run:

          $ MYVAR          =          hullo
$
./ myvar2 . sh
MYVAR is
:
MYVAR is
: hullo there

It'southward still not been set! What's going on?!
When you telephone call myvar2.sh from your interactive shell, a new shell is spawned to run the script. This is partly because of the #!/bin/sh line at the outset of the script, which we discussed earlier.
We need to export the variable for it to be inherited by some other programme - including a shell script. Type:

          $                    export                      MYVAR
$
./ myvar2 . sh
MYVAR is
: hi
MYVAR is
: hullo in that location

Now wait at line 3 of the script: this is changing the value of MYVAR. Simply in that location is no style that this will exist passed back to your interactive shell. Endeavor reading the value of MYVAR:

          $                    repeat                      $MYVAR
hello
$

Once the shell script exits, its environment is destroyed. Simply MYVAR keeps its value of hello within your interactive beat.
In order to receive surround changes back from the script, we must source the script - this finer runs the script inside our own interactive vanquish, instead of spawning another trounce to run it.
We can source a script via the "." (dot) command:

          $ MYVAR          =          hello
$
echo $MYVAR
hi
$
. ./ myvar2 . sh
MYVAR is
: hello
MYVAR is
: hello in that location
$
echo $MYVAR
hi there

The change has at present made it out into our shell again! This is how your .profile or .bash_profile file works, for instance.
Notation that in this case, we don't need to consign MYVAR.
Cheers to sway for pointing out that I'd originally said echo MYVAR above, not repeat $MYVAR equally it should be. Another case of an piece of cake mistake to make with shell scripts. I other thing worth mentioning at this point virtually variables, is to consider the post-obit shell script:


          #!/bin/sh                      
echo "What is your name?"
read USER_NAME
echo "Hello $USER_NAME"
echo "I volition create you a file chosen $USER_NAME_file"
touch $USER_NAME_file

Call up about what effect you lot would expect. For example, if you enter "steve" every bit your USER_NAME, should the script create steve_file?
Actually, no. This will cause an error unless in that location is a variable called USER_NAME_file. The shell does not know where the variable ends and the rest starts. How can we define this?
The answer is, that we enclose the variable itself in curly brackets:


user.sh

          #!/bin/sh                      
echo "What is your name?"
read USER_NAME
repeat "Hello $USER_NAME"
echo "I will create y'all a file called ${USER_NAME}_file"
impact "${USER_NAME}_file"

The shell now knows that we are referring to the variable USER_NAME and that nosotros want it suffixed with "_file". This can be the downfall of many a new beat out script programmer, equally the source of the trouble can be difficult to runway downward.

Also note the quotes around "${USER_NAME}_file" - if the user entered "Steve Parker" (note the space) then without the quotes, the arguments passed to touch would be Steve and Parker_file - that is, we'd effectively exist saying touch on Steve Parker_file, which is 2 files to be affected, not ane. The quotes avoid this. Thanks to Chris for highlighting this.

RSS Feed Share on Twitter
Dorsum: A Showtime Script Next: Wildcards

Books and eBooks

Contact

Y'all can postal service me with this form. If you wait a respond, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the cease of the form, to prove that you are a real person!

griffindrivishe.blogspot.com

Source: https://www.shellscript.sh/variables1.html

0 Response to "Bash Is Reading Varible as a Command and Not a String"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel