Accept options when installing Java in terminal

How can I install Java (OpenJDK) on an Ubuntu system with regional preferences set int the command itself, so that it runs through the complete setup without needing user input? I am using this command:

sudo apt install openjdk-11-jdk -y

This always waits for input where I have to select preference for region, where I select 1 for Americas and then 85 for Los_Angeles. Can I include this as a part of a command somehow, so that I can automate this?


Solution 1:

Use expect. It is a program that simulates terminal input in programs that interactively ask for data. Great tool for automation. You can install it with sudo apt install expect.

Because I don't know what exact questions the openjdk installer asks, I would use a fictional example of a program someprogram that asks two questions, Enter your name: and Enter your age: and then does something (not asking for any more input). If you want to automatically provide answers to these questions, the script will look like this:

#!/usr/bin/expect

spawn someprogram
expect "name:"
send "John\r"
expect "age:"
send "42\r"
wait

The spawn command runs your program, expect tells the script to wait until the specified string appears in the program output, send tells the script to send specified string to the program (\r is Enter), and wait waits until the program terminates.