0

I'm writing a shell script as below.

#/bin/bash

ip1="1.1.1.1"
ip2="2.2.2.2"

for ((i=1; i<=2; i++))
do
echo "$[ip$i]"

done

i get the error after run.
./1.sh: line 8: 1.1.1.1: syntax error: invalid arithmetic operator (error token is ".1.1.1")

Thank you so much !

0

1 Answer 1

2

Use indirect variable expansion.

#/bin/bash

ip1="1.1.1.1"
ip2="2.2.2.2"

for ((i=1; i<=2; i++))
do
  var="ip$i"
  echo "${!var}"
done

However, a better idea is to use an array.

ips=( "1.1.1.1" "2.2.2.2" )
for ip in "${ips[@]}"; do
   echo "$ip"
done

for ((i=1; i<=${#ip[@]}; i++)); do
   echo "${ips[i]}"
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.