0% found this document useful (0 votes)
9 views4 pages

Basic Shell Script for Number Check

Uploaded by

yashsadafal502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

Basic Shell Script for Number Check

Uploaded by

yashsadafal502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

writing and executing a basic shell script that uses an `if` statement.

This script will check if a given


number is positive, negative, or zero.

#!/bin/bash

# Prompt user to enter a number

echo "Enter a number: "

read number

# Check if the number is positive, negative, or zero

if [ "$number" -gt 0 ]; then

echo "The number is positive."

elif [ "$number" -lt 0 ]; then

echo "The number is negative."

else

echo "The number is zero."

fi

```

### Explanation:

1. **Shebang (`#!/bin/bash`)**: Indicates that the script should be executed using the Bash shell.

2. **Prompt and Read Input**:

- `echo "Enter a number: "` prompts the user to input a number.

- `read number` reads the user input and stores it in the variable `number`.
3. **If Statement**:

- `[ "$number" -gt 0 ]`: Checks if the number is greater than 0 (positive).

- `[ "$number" -lt 0 ]`: Checks if the number is less than 0 (negative).

- `else`: Covers the case where the number is zero.

4. **Output**:

- Depending on the condition, it prints whether the number is positive, negative, or zero.

### Steps to Execute the Script:

1. **Create the Script**:

- Use a text editor to create the script file. For example, using `nano`:

```sh

nano check_number.sh

```

- Paste the script into the editor and save the file (`Ctrl + X`, then `Y`, then `Enter`).

2. **Make the Script Executable**:

- Change the file permissions to make it executable:

```sh

chmod +x check_number.sh

```

3. **Run the Script**:


- Execute the script by typing:

```sh

./check_number.sh

```

- You will be prompted to enter a number, and the script will output whether the number is positive,
negative, or zero based on the conditions defined in the `if` statement.

Here's how the script might look when executed:

```sh

$ ./check_number.sh

Enter a number:

The number is positive.

```

or

```sh

$ ./check_number.sh

Enter a number:

-3

The number is negative.

```
or

```sh

$ ./check_number.sh

Enter a number:

The number is zero.

```

Feel free to modify the script for more complex conditions or additional functionality as needed!

You might also like