kuti
kuti

Reputation: 87

How to set a default value in an IF snippet?

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 I am trying to get that if the user hits the enter key, the Port should be set to 389. The snippet above does not seem to be working.

Any suggestions?

Upvotes: 3

Views: 133

Answers (5)

jim mcnamara
jim mcnamara

Reputation: 16389

Another way with just the shell -- try parameter substitution:

read port
port=${port:-389}

Upvotes: 0

Kenster
Kenster

Reputation: 25399

It's not exactly what you asked, but Solaris has a set of utilities for this sort of thing.

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

Check out the other /usr/bin/ck* utilities to prompt the user for other types of data, including things like files or user names.

Upvotes: 0

alanc
alanc

Reputation: 4180

If the user enters nothing then $PORT is replaced with nothing - the ancient convention for making this work with the original Bourne shell is:

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

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

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

or even

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

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

If you pass -e to read then you can use -i to specify an initial value for the prompt.

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 360105

This prompts the user for input and if enter is pressed by itself, sets the value of port to a default of "389":

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

Upvotes: 1

Related Questions