How to set default value in IF fragment?

I have the following snippet in a bash script written in Solaris 10:

printf "port(389)="
read PORT
  if [[ $PORT == "" ]]; then
     PORT=389
  fi

What am I trying to get if the user presses the enter key, the port should be set to 389. The above snippet does not work.

Any suggestions?

+3
source share
5 answers

This is not exactly what you requested, but Solaris has a set of utilities for this kind of thing.

PORT=`/usr/bin/ckint -d 389 -p 'port(389)=' -h 'Enter a port number'`

Check other utilities / usr / bin / ck * to request other types of data from the user, including things like files or usernames.

0
source

This triggers a user request, and if the input is pressed on its own, sets the portdefault value to "389":

read -rp "port(389)=" port
port="${port:-389}"
+1

-e read, -i, .

0
source

If the user does not enter anything, then it $PORTis replaced with nothing - an ancient convention for creating this work with the original Bourne shell:

if [ "x$PORT" == "x" ]; then

Although more modern shells (i.e. actual bash, but not Solaris 10 / bin / sh, which are the ancient Bourne shell) should be able to deal with:

if [[ "$PORT" == "" ]]; then

or even

if [[ -z "$PORT" ]]; then
0
source

Another way with the shell is to try replacing the parameters:

read port
port=${port:-389}
0
source

Source: https://habr.com/ru/post/1747712/


All Articles