0

I am looking to modify bash script to set variable by either command line argument or from user input (read command). if argument passed as command line, script should be executed without asking for user input.

I am able to set variable either command line argument or user input but not both way in same script

#!/bin/sh

ENVIRONMENT_NAME=$1
EMAIL=$2

read ENVIRONMENT_NAME
read EMAIL

echo "$ENVIRONMENT_NAME"
echo "$EMAIL" 

if I execute like below read command should take values from $1 and $2.

./<scriptname> <environment_name> <email>
  • What's your expectation if the user only supplies one variable as an argument? What if they only want to provide the email as an argument? – Jeff Schaller Jul 1 at 16:01
  • I will add condition which check that both values should be provided. if its not provided script will be terminated. – Ankit Goyal Jul 1 at 16:27
0

Well. You have to add a check whether positional vars are set or not. If not, then ask for use input.

Something like this:

#!/bin/sh

[ -n "$1" ] && ENVIRONMENT_NAME=$1 || { echo -n "Enter environment name: "; read ENVIRONMENT_NAME; }
if [ -n "$2" ]; then
        EMAIL=$2
else
        echo -n "Enter email: "
        read EMAIL
fi


echo "env=$ENVIRONMENT_NAME"
echo "email=$EMAIL"

Note that I used different constructions for conditional check, just to show that there are different ways and you might pick the one which is more convenient for you.

Also note, that the one with || && should be used more careful, as it might fall to || ... even in case something goes wrong in the part between && .. ||.

  • echo -n isn't portable; some versions of echo will print "-n" as part of their output. (I once had to rewrite a bunch of my scripts after an OS update changed this...) I'd recommend using printf instead (either printf "Enter email: " or printf '%s' "Enter email: "). – Gordon Davisson Jul 1 at 17:56
1

To check whether an argument is provided, you would look at the value of $# (the number of arguments):

#! /bin/sh -

if [ "$#" -ge 1 ]; then
  ENVIRONMENT_NAME=$1
else
  IFS= read -r ENVIRONMENT_NAME || exit # on EOF
fi

if [ "$#" -ge 2 ]; then
  EMAIL=$2
else
  IFS= read -r EMAIL || exit # on EOF
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.