Bash structured language constructs

From Linux Shell Scripting Tutorial - A Beginner's handbook
Revision as of 15:05, 1 September 2009 by Admin (talk | contribs) (Created page with 'Yo can use the if command to test a condition. For example, shell script may need to execute tar command only if a certain condition exists (such as bakcup only on Friday night).…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Yo can use the if command to test a condition. For example, shell script may need to execute tar command only if a certain condition exists (such as bakcup only on Friday night).

If today is Friday
   execute tar command
otherwise
   print an error message on screen.

.

More About Logic

  • So far, the script you've used followed sequential flow.
  • Each command and/or statement is executed once, in order.
  • With sequential flow scripts you cannot write complex applications or intelligent Linux scripts.
  • However, with if command you will be able to selectively run certain commands of your script.
  • You can create warning message and run script more interactively using if command to execute code based on a condition.

But What Is A Condition?

  • A condition is nothing but an expression that evaluates to a boolean value.
  • In other words condition can be either true or false.
  • A condition is used in shell script loops and if statements.

So, How Do I Make One?

A condition is mainly a comparison between two values. Open a shell prompt (console) and type the following command:

<syntax lang="bash">echo $(( 5 + 2 ))

Sample Output:

7

Addition is 7. But,

<syntax lang="bash">echo $(( 5 < 2 ))

Sample Output:

0

Answer is zero (0). Shell simple compared two number and returned result as true or false. Is 5 is less than 2? No. So 0 is returned. In shell:

  • 0 indicates false.
  • 1 or (non-zero) value indicate true.