tags:

views:

41

answers:

5

Hello,

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?

+1  A: 

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}"
Dennis Williamson
I could not paste the hole code in here because it is a part of a bigger script that deals with creating certificates for a Directory Server. But I am using "certutil" for Directory Server to accept inputs from user based on questions like "Organization", "City", "Country", etc. Port is one of them. Used in the following way:$DSBIN/certutil -d $BASE_DIR/`hostname`/alias -P slapd- -x -S -n $NAME -s cn=$CN,cn=$PORT,st=$STATE,C=$COUNTRY,L="$CITY" -t CTu,u,u -v $MONTHwith my original if statement, the system is throwing a "bad database" error and this happens if one ore more entries are invalid
kuti
And your snippet works without a problem for some reason....
kuti
In reality, my snippet and your snippet function essentially identically (one exception is that mine has the `-r` option for `read`). You might try putting a `set -x` before and a `set +x` after the section of your code that is causing problems. This will cause a trace to be displayed which shows variable expansions among other things. It might help track down the problem.
Dennis Williamson
A: 

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

Ignacio Vazquez-Abrams
The `-i` option to `read` is new in Bash 4.
Dennis Williamson
A: 

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
alanc
A: 

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.

Kenster
This is actually what I was trying to get to. Wonderful thank you.
kuti
A: 

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

read port
port=${port:-389}
jim mcnamara