Here are the steps to write a simple Bash script that checks if a given number is even or odd:
1. Create a new file as mentioned below.
vi check_number.sh
2. Copy and paste below simple Bash script that prompts the user for a file name, reads the contents of the specified file, and displays them on the terminal.
#!/bin/bash # Prompt the user for a number echo "Enter a number:" read number # Check if the number is even or odd if ((number % 2 == 0)); then echo "$number is even." else echo "$number is odd." fi
Now, let’s break down the script:
1. Shebang (#!/bin/bash):
– This line indicates that the script should be executed using the Bash shell.
2. Prompt for User Input:
– echo “Enter a number:” prompts the user to enter a number.
– read number reads the user’s input and stores it in the variable number.
3. Check if Number is Even or Odd:
– if ((number % 2 == 0)); then checks if the remainder of the number divided by 2 is equal to 0.
– If the condition is true, it means the number is even.
4. Display Result:
– echo “$number is even.” is executed if the number is even.
– else is part of the conditional statement and is executed if the number is odd.
– echo “$number is odd.” is executed if the number is odd.
3. Save and close the “vi” editor by pressing “Esc” key and type :wq! and press “enter” key.
4. Make sure to give execute permissions to the script before running it. You can do this by running the following command in the terminal:
chmod +x check_number.sh
Note : Replace “check_number.sh” with the actual name you save the script as.
The script will prompt you to enter a number, and it will then tell you whether the number is even or odd.
How do you feel about this post? Drop your comments below..