1

I would like to make a chat bot using bash. And I was just wondering if anyone in the community knows of a proper / preferred method for storing user input as a variable in a shell script.

For example: if my chat bot doesn't recognize the request made to it, is there a way to ask the user to give the program the correct answer in future and then store that answer as a variable, without having to manually edit the script?

Perhaps with the read command or similar?

2 Answers 2

1

Bash is not really a preferable language to write high level applications. Its strengths are in interacting with system commands and automating stuff, not that much in implementing complex business logic or doing stuff like networking. You'd make your life easier by looking into a more appropriate language for this, like e.g. Python. Anyway, of course it's possible to do that with Bash, just more difficult, especially for a beginner.

So to get back to your actual question, yes, you can use the read shell built-in to request user input and store it in shell variables, like:

read line 
echo "You said <$line>"

Example run, including user input:

Hello there                                    ← this is user input
You said <Hello there>                         ← this is the output

With these two commands, I first wait for one line of user input and store it in a variable I called $line. Then I can output the variable again with the second command.

Type help read to get a full description of the read command and its available options.


You could use that in a loop to validate the input and keep asking until the answer is acceptable:

while [[ "$my_color" != "blue" && "$my_color" != "red" ]] ; do 
    read -p "Pick blue or red: " my_color
done
echo "You picked $my_color."

Example run, including user input:

Pick blue or red: green
Pick blue or red: 
Pick blue or red: red
You picked red.

There are more elegant ways to write menus which provide you a choice between a number of predefined options though, e.g. using select. See How can I create a select menu in a shell script? for more info about that.

0

You can check some guides on how to make select menu in bash. However there is a rule I and other devs/sys admins follow and its the following: If the script is longer than 200 lines rewrite in python/perl/whatever just not bash. Bash isn't good enough for high end applications it's fine for interacting with basic system commands, but that's all.

1
  • I appreciate the pointers man. that's good to know for sure
    – user797940
    Nov 9, 2018 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.