Home > Blockchain >  Assigning one variable to another in Bash
Assigning one variable to another in Bash

Time:11-04

ip="192.168.1.1"

if [ -n "$(ip = 192.168.1.1)" ];
then
IPADDR=$(ip addr show |grep 'inet '|grep -v 127.0.0.1 |awk '{print $2}'| cut -d/ -f1)
else
"${ip}"="${IPADDR}"
fi
echo "${IPADDR}"

Im trying to assigning ip="192.168.1.1" to variable IPADDR

the error im geting atm is Object "=" is unknown, try "ip help". ./test: line 7: 192.168.1.1=: command not found

CodePudding user response:

Here ...

if [ -n "$(ip = 192.168.1.1)" ];

... you are executing the command ip, passing arguments = and 192.168.1.1, and capturing its standard output. These are not valid arguments for that command, so ip emits an error message to its standard error, but nothing to its standard output.

The test [ -n "$(ip = 192.168.1.1)" ] evaluates whether the captured output is non-empty, so this test fails, and consequently, the else block is executed. Here ...

"${ip}"="${IPADDR}"

... is not a variable assignment but rather a command, because the text to the left of the = is not (just) an identifier. The IPADDR variable is unset or null, so that expands to 192.168.1.1=. The shell reports that there is no command of that name.

It's hard to be sure what you were really trying to accomplish, but going with the question title, if you want to assign a value to a variable then the syntax is

variable_name=value

The variable_name must be an identifier. The value is subject to expansion and quote removal, but not word splitting, so either of these would work for what you appear to be trying to do

ip="${IPADDR}"

or

ip=${IPADDR}

. With that said, the code does not make sense, because it does not assign a value to variable IPADDR before attempting that assignment.

Earlier, it is possible that you meant

if [ "$ip" != 192.168.1.1 ]

... which tests whether the value of variable $ip, considered as a string, is equal to the string 192.168.1.1. Even then, however, the code does not make sense overall.

  • Related