How to assign value to input variable in shell

10,731

Solution 1

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.

Solution 2

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.
Share:
10,731

Related videos on Youtube

Aquarius24
Author by

Aquarius24

Updated on September 18, 2022

Comments

  • Aquarius24
    Aquarius24 almost 2 years

    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?

    • don_crissti
      don_crissti almost 8 years
    • MatthewRock
      MatthewRock almost 8 years
      Why are you trying to do this? Looks a bit like the XY problem.
    • Gilles 'SO- stop being evil'
      Gilles 'SO- stop being evil' almost 8 years
      @MatthewRock There's a very clear use case which is to provide a default value for some parameters.
  • Aquarius24
    Aquarius24 almost 8 years
    why are you giving $1 in the second line while setting instead of $2?
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' almost 8 years
    @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.