Variables
With simple variables, you can...
- save values using =
- find those values putting $ in your echo
"One Look Is Worth A Thousand Words"
#/bin/bash
var="Yes, did it!"
echo "Have you done it? $var"
The result of running this script is:
Have you done it? Yes, did it!
Talking to the user
But let's do something useful with this concepts. Imagine you can only show the date for the user if he knows the secret password! You might want to ask him the password, so do it by using the command read.
Then, if the user type the easiest ever right password "dog", the date is shown, otherwise, the program is closed. Let's have a look at the code before anything.
#/bin/bash
echo "What's THE SECRET PASSWORD?"
#Puts the user's answer in the variable answer
read answer
#If answer is dog dog, print date!
test "$answer" == "dog" && date
Now, gotta understand it:
- The operator == means equals to
- The operator && means and
As we had already saved the user's answer in the variable $answer with the command read, when we compare the variable $answer to "dog", if they are the same, it prints the date; else, it finishes the program (because there are no more commands to execute).
Therefore, the result of the script must be both below:
With the right password:
What's THE SECRET PASSWORD?
dog
Ter Jul 17 23:32:39 -03 2018
With the wrong password:
What's THE SECRET PASSWORD?
cat
I'm not convinced!
So let's crack this code a bit more!
#/bin/bash
echo "What's THE SECRET PASSWORD?"
#Puts the user's answer in the variable answer
read answer
#REVERSE LOGIC!
#If answer is not dog, exit; Else, print date!
test "$answer" != "dog" && exit
date
Stuff is different here:
- The operator != means different
Now we use the reverse logic to do the same thing. This time, the command exit can only happen if the user's answer is different from "dog". Otherwise, it will continue running the script and eventually reach the command date.
The result is exactly the same as in the previous script!
About
You can find all my scripts in my github!
Follow me for more articles!
Top comments (1)
Hi ,
I have a small requirement using shell script in Linux.
i) Connect to postgres DB.
ii) Run a sql script.
Please can help me out to do this.