How to write bash script or automate the open vi and edit document?

vi is by definition a visual editor.

In this case it's probably better to use some other means.

If you only want to append those lines, do something like:

cat >> filename.sh <<'EOF'
export GRADLE_HOME=/opt/gradle/gradle-5.2.1
export PATH=${GRADLE_HOME}/bin:${PATH}
EOF

This will also work if the file doesn't exist yet.

If you want those lines added at the beginning, you can use ed which is a line-oriented editor:

ed filename.sh <<'EOF'
1i
export GRADLE_HOME=/opt/gradle/gradle-5.2.1
export PATH=${GRADLE_HOME}/bin:${PATH}
.
w
q
EOF

This instructs ed to insert lines at line 1; the solitary dot . on the line indicates the end of input, so insertion stops there. Finally the file is written (w) and the edit session quitted (q).

If you insist on using ed even if the file doesn't exist yet (in which case I would use the cat example above), you can use this:

ed filename.sh <<'EOF'
i
export GRADLE_HOME=/opt/gradle/gradle-5.2.1
export PATH=${GRADLE_HOME}/bin:${PATH}
.
w filename.sh
q
EOF

The main difference is that you don't pass a line number with the i insert command, as there are no lines yet; and you pass a filename to the w write command which is the new file.

sed can also be used, but for such tasks I find ed easier to use (and to read what's happening).