Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Guess the price of Linux-shell fun

Shulou Source: shulou.com Published: 2022-06-01 04:28:19 09月27日 Update

Case requirements:

A random number of prices (0-999) is pre-generated by the script as the actual price

Judge whether the price guessed by the user is higher or lower than the actual price, and ask the user to guess again after giving the corresponding prompt.

Until the user guesses the actual price, the number of times the user guesses and the actual price are output.

The steps of the experiment:

1. Write a script with an arbitrary name, shell.sh:

The screenshot is as follows:

The contents are as follows:

#! / bin/bash

PRICE=$ (expr $RANDOM 1000)

TIMES=0

Echo "the actual price of the commodity is between 0-999, guess what it is?"

While true

Do

Read-p "Please enter the number of prices you guess:" INT

Let TIMES++

If [$INT-eq $PRICE]

Then

Echo "Congratulations on your correct answer, the actual price is $PRICE"

Echo "you guessed a total of $TIMES times"

Exit 0

Elif [$INT-gt $PRICE]

Then

Echo "too high!"

Else

Echo "too low!"

Fi

Done

2. Add x permissions to the script, and execute the script to view the execution of the script:

In fact, there are a lot of real fun in the script, learn to be flexible and follow suit.

Attached:

You can view environment variables with the env or export command

Use the set command to view all variables (including environment and custom variables)

Use the unset command to delete a variable

Most versions of the LINUX system have a random number generator, the / dev/random file.

Random numbers can be obtained randomly through the system environment variable $RANDOM associated with this random number file.

In the BASH environment, the content of this RANDOM variable is between 0Murray 32767 (man bash, search RANDOM for instructions)

Therefore, as long as echo $RANDOM, the system will take the initiative to randomly pick up a value between 0Murray 32767.

For example, when you want to have a random number between 0Mel 9, you can declare the numeric type with declare

Welcome to the official account of Wechat: Xiao Wen study Society.

Tags: Price variable script actual guess environment user random number between command system content numerical value number file generation fun inference yes meeting host Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Docker OPPO Reno MariaDB Shulou Information