2

I am asking user for input and taking input in the variables such as $1, $2 etc. I am checking the variable for null value and wants to replace the value if null.

if [ "$2" == "" ]; then
2=value
fi

But something I am missing. Any suggestions?

2

You can't directly set values to the positional paramaters like this.

You can set them with the set command, but this will set all the values ($1, $2, ...)

e.g.

$ set -- first second third fourth fifth
$ echo $1
first
$ echo $2
second

Now there are two cases where $2 can be the empty string; first if no value has been passed, or second if "" is passed as an actual argument and so there may still be a $3, $4 etc.

We can handle each case in a slightly complicated way:

#!/bin/bash

echo Before 1=$1 2=$2 3=$3 4=$4

if [ -z "$2" ]
then
  first=$1
  shift 2
  set -- "$first" value "$@"
fi

echo After 1=$1 2=$2 3=$3 4=$4

The bit inside the if test will ensure all other values are retained.

e.g.

% ./testing arg1 "" "arg 3" "and arg 4"
Before 1=arg1 2= 3=arg 3 4=and arg 4
After 1=arg1 2=value 3=arg 3 4=and arg 4

But you might be able to do things simpler and just use ${2:-value} which will evaluate to value if $2 is not set, so then you don't need to worry about rewriting the arguments.

| improve this answer | |
1

try

if [ -z "$2" ]; then
   set "$1" value
fi
  • see man test (an alternative is [ "x$2" == x ]
  • set will position parameter, to position as second parameter, $1 must be recalled as first one.
| improve this answer | |
  • why are you giving $1 in the second line while setting instead of $2? – Aquarius24 Jul 20 '16 at 11:21
  • 1
    @Aquarius24 Because set "$1" value doesn't set $1 to value, it sets $1 to $1 (so $1 is left unchanged) and $2 to value. Similarly set value would set $1 to value (and make $2, $3, etc. unset). set one two three sets $1 to one, $2 to two and $2 to three. – Gilles 'SO- stop being evil' Jul 20 '16 at 21:15

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.