If then linux scripting

Bash if..else Statement

This tutorial will walk you through the basics of the Bash if Statement and show you how to use it in your shell scripts.

Decision-making is one of the most fundamental concepts of computer programming. Like in any other programming language, if , if..else , if..elif..else , and nested if statements in Bash are used to execute code based on a certain condition.

if Statement #

Bash if conditionals can have different forms. The most basic if statement takes the following form:

if TEST-COMMAND then  STATEMENTS fi 

The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword.

If the TEST-COMMAND evaluates to True , the STATEMENTS gets executed. If TEST-COMMAND returns False , nothing happens; the STATEMENTS get ignored.

In general, it is a good practice always to indent your code and separate code blocks with blank lines. Most people choose to use either 4-space or 2-space indentation. Indentations and blank lines make your code more readable and organized.

Let’s look at the following example script that checks whether a given number is greater than 10:

#!/bin/bash  echo -n "Enter a number: " read VAR  if [[ $VAR -gt 10 ]] then  echo "The variable is greater than 10." fi 

Save the code in a file and run it from the command line:

The script will prompt you to enter a number. If, for example, you enter 15, the test command will evaluate to true because 15 is greater than 10, and the echo command inside the then clause will be executed.

The variable is greater than 10. 

if..else Statement #

The Bash if..else statement takes the following form:

if TEST-COMMAND then  STATEMENTS1 else  STATEMENTS2 fi 

If the TEST-COMMAND evaluates to True , the STATEMENTS1 will be executed. Otherwise, if TEST-COMMAND returns False , the STATEMENTS2 will be executed. You can have only one else clause in the statement.

Let’s add an else clause to the previous example script:

#!/bin/bash  echo -n "Enter a number: " read VAR  if [[ $VAR -gt 10 ]] then  echo "The variable is greater than 10." else  echo "The variable is equal or less than 10." fi 

If you run the code and enter a number, the script will print a different message based on whether the number is greater or less/equal to 10.

if..elif..else Statement #

The Bash if..elif..else statement takes the following form:

if TEST-COMMAND1 then  STATEMENTS1 elif TEST-COMMAND2 then  STATEMENTS2 else  STATEMENTS3 fi 

If the TEST-COMMAND1 evaluates to True , the STATEMENTS1 will be executed. If the TEST-COMMAND2 evaluates to True , the STATEMENTS2 will be executed. If none of the test commands evaluate to True , the STATEMENTS2 is executed.

You can have one or more elif clauses in the statement. The else clause is optional.

The conditions are evaluated sequentially. Once a condition returns True , the remaining conditions are not performed, and program control moves to the end of the if statements.

Let’s add an elif clause to the previous script:

#!/bin/bash  echo -n "Enter a number: " read VAR  if [[ $VAR -gt 10 ]] then  echo "The variable is greater than 10." elif [[ $VAR -eq 10 ]] then  echo "The variable is equal to 10." else  echo "The variable is less than 10." fi 

Nested if Statements #

Bash allows you to nest if statements within if statements. You can place multiple if statements inside another if statement.

Читайте также:  Linux изменения права доступа папок

The following script will prompt you to enter three numbers and print the largest number among the three numbers.

#!/bin/bash  echo -n "Enter the first number: " read VAR1 echo -n "Enter the second number: " read VAR2 echo -n "Enter the third number: " read VAR3  if [[ $VAR1 -ge $VAR2 ]] then  if [[ $VAR1 -ge $VAR3 ]]  then  echo "$VAR1 is the largest number."  else  echo "$VAR3 is the largest number."  fi else  if [[ $VAR2 -ge $VAR3 ]]  then  echo "$VAR2 is the largest number."  else  echo "$VAR3 is the largest number."  fi fi 

Here is how the output will look like:

Enter the first number: 4 Enter the second number: 7 Enter the third number: 2 7 is the largest number. 

Multiple Conditions #

The logical OR and AND operators allow you to use multiple conditions in the if statements.

Here is another version of the script to print the largest number among the three numbers. In this version, instead of the nested if statements, we’re using the logical AND ( && ) operator.

#!/bin/bash  echo -n "Enter the first number: " read VAR1 echo -n "Enter the second number: " read VAR2 echo -n "Enter the third number: " read VAR3  if [[ $VAR1 -ge $VAR2 ]] && [[ $VAR1 -ge $VAR3 ]] then  echo "$VAR1 is the largest number." elif [[ $VAR2 -ge $VAR1 ]] && [[ $VAR2 -ge $VAR3 ]] then  echo "$VAR2 is the largest number." else  echo "$VAR3 is the largest number." fi 

Test Operators #

In Bash, the test command takes one of the following syntax forms:

test EXPRESSION [ EXPRESSION ] [[ EXPRESSION ]] 

To make the script portable, prefer using the old test [ command, which is available on all POSIX shells. The new upgraded version of the test command [[ (double brackets) is supported on most modern systems using Bash, Zsh, and Ksh as a default shell.

To negate the test expression, use the logical NOT ( ! ) operator. When comparing strings , always use single or double quotes to avoid word splitting and globbing issues.

Below are some of the most commonly used operators:

  • -n VAR — True if the length of VAR is greater than zero.
  • -z VAR — True if the VAR is empty.
  • STRING1 = STRING2 — True if STRING1 and STRING2 are equal.
  • STRING1 != STRING2 — True if STRING1 and STRING2 are not equal.
  • INTEGER1 -eq INTEGER2 — True if INTEGER1 and INTEGER2 are equal.
  • INTEGER1 -gt INTEGER2 — True if INTEGER1 is greater than INTEGER2 .
  • INTEGER1 -lt INTEGER2 — True if INTEGER1 is less than INTEGER2 .
  • INTEGER1 -ge INTEGER2 — True if INTEGER1 is equal or greater than INTEGER2.
  • INTEGER1 -le INTEGER2 — True if INTEGER1 is equal or less than INTEGER2 .
  • -h FILE — True if the FILE exists and is a symbolic link.
  • -r FILE — True if the FILE exists and is readable.
  • -w FILE — True if the FILE exists and is writable.
  • -x FILE — True if the FILE exists and is executable.
  • -d FILE — True if the FILE exists and is a directory.
  • -e FILE — True if the FILE exists and is a file, regardless of type (node, directory, socket, etc.).
  • -f FILE — True if the FILE exists and is a regular file (not a directory or device).
Читайте также:  Scripting languages used in linux

Conclusion #

The if , if..else and if..elif..else statements allow you to control the flow of the Bash script’s execution by evaluating given conditions.

If you have any questions or feedback, feel free to leave a comment.

Источник

Linux if then else bash Script with Examples

Linux if then else allows you to build a branch in a script and create conditional logic (so it is not technically a command, but a keyword).

  1. Purpose — Learn what if is for and how to find help.
  2. Options — Review a few common options and arguments.
  3. Examples — Walk through code examples with if.
  4. Script — Add if to our script and run it.
  5. A tip — Finish off with one more insight.

face pic

by Paul Alan Davis, CFA

In this tutorial on Linux if then else, 94 of 100, below find a 3-4 minute introductory video, a text-based tutorial and all of the code examples from the video.

An ad-free and cookie-free website.

Examples of the Linux if Command (Keyword)

Learn to build a branch in a bash script at the Linux command line.

Video Tutorial

Videos can also be accessed from the Linux Essentials Playlist on YouTube.

Linux if then else bash Script with Examples (3:55)

Video Script

The Command and Why You Need It

Our ninety-fourth word, or command to memorize is if from our category Workflow.

if (plus other keywords) allows you to build a branch in a script.

Common Linux if Options

Recall from videos (tutorials) #87 to #93, we’re using a script to demonstrate workflow, now we’ll introduce if at the command line and then script it.

Before we start, it helps to think of commands as mini programs and most follow this structure: command -option(s) argument(s) .

The if command (condition/keyword) has no traditional options and no arguments as it has its own syntax, and our structure here has been command-based, but if is a technically a bash keyword, not a command and I’ll explain it with 4 other related keywords: then , else , elif and fi .

Unlike most commands, help is not available with double-dash —help , as the if construct is a shell built-in covered in the bash man page.

So why is if an important command (keyword)? Well, we need to tell bash to follow conditional logic. And now you know how to do that.

Demonstration

Okay, the best way to embed this in your memory is by typing in your own terminal window.

Find this on your Mac using a program called Terminal. On Linux use Terminal or Konsole, and currently Microsoft is adding this functionality to Windows.

Here we go. Let’s review the 5 words in this group that I mentioned earlier.

$ type if; type then; type else; type elif; type fi if is a shell keyword then is a shell keyword else is a shell keyword elif is a shell keyword fi is a shell keyword

And as you can see, they all are keywords.

Next, try an if on one line, with integers and incorporate the brackets from that video (tutorial) we just did on test . And we have to assume an input variable here, and let’s use myinput=1 .

And then the logic goes, if myinput=1 , then input was 1, and your exit status was 0 for true, and it ends there with fi . (At the command line you can use the ; to separate the steps. It always ends with fi and will get there if the condition is true and it will go to the second step, or if false, it will skip the second step and go straight to the third, or fi .)

Читайте также:  Broadcom bluetooth driver linux

Next, let’s change myinput to 2, and then re-run this line here.

And it skipped to the fi to end (and had no output) because the exit status was not true (not zero).

And then, since this line is getting very long, let’s view it in our script and pause to review this menu and logic for the branches here, and then we’ll try it out.

(Below is the screen from within nano .)

GNU nano 2.2.6 File: /home/factorpad/bin/funscript if [[ «$yourpick» =~ 3 ]]; then if [[ $yourpick == 1 ]]; then printf «\n\tYou Selected 1. One moment please. \n» sleep 2s fun_status continue fi if [[ $yourpick == 2 ]]; then printf «\n\tYou selected 2. One moment please. \n» sleep 2s fun_returns continue fi if [[ $yourpick == 3 ]]; then printf «\n\tYou selected 3. One moment please. \n» sleep 2s fun_summary continue fi if [[ $yourpick == 4 ]]; then printf «\n\tYou selected 4.\n» sleep 1s printf «\n\tThank you for your time.\n» sleep 1s printf «\n\tLet’s finish up. \n» sleep 2s fun_finish break fi if [[ $yourpick == 5 ]]; then printf «\n\tYou selected 5.\n» sleep 1s echo -e «\n\tThank you, have a nice day.» sleep 1s break fi else printf «\n\tInvalid input. Please try again\n» sleep 2s continue fi ^G Get Help ^0 WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell

(Please note: the code above is meant to illustrate the concept of a multi-level conditional statement. It will not run without other code in the script. Go to the last video #100 to see the code for the whole script if you’d like to try it on your own.)

(Hit Ctrl-x to leave nano and y to confirm saving.)

And last, run it with ~/bin/funscript and here’s our progress so far.

$ ~/bin/funscript The current date and time: Mon Nov 22 18:22:42 PST 2016 What is your name? Paul Thank you Paul (several lines trimmed)

(The section below is after the pause and clear screen.)

Please select from the following options: (1) Show system status (2) Collect returns data (3) See a sample of the data (4) Finish the Linux Essentials playlist (5) Quit Your choice: 5 You selected 5. Thank you, have a nice day. $ _

A Final Tip

Okay now you know how to use if . And you know the syntax for commands, options and arguments.

One last tip about the if command (keyword). So at the end there, I left with the #5 to quit because I built a loop, and the first few choices sit in that loop, and I’ll explain that next.

Okay, thanks for visiting today. I hope this was a helpful introduction to the if command (keyword).

Learn More About The Series

For an overview of the 100 videos, the 8 quizzes, a cheat sheet, the categories and a Q&A section, visit:

What’s Next?

See other scripts and programs built in other languages at our YouTube Channel and throughout this website.

  • For the Outline to all 100 tutorials, click Outline.
  • To go back to the printf command, hit Back.
  • Contribute to new content for this free site, click Tip.
  • To learn another important shell script programming concept called a function , click Next.

Источник

Оцените статью
Adblock
detector