0

how to use two variables in a for loop in a shell script.

Below is the id and name of the projects got using jq operation.

Netbank734113 8a70803f8045722601804f62d54c5d9d
Netbank734112 8a70801c804568ae01804f625a923f8d

Have separated name and Id in different variables using the below commands

projectname=$(echo "$runIds" | awk '{print $1}')
projectId=$(echo "$runIds" | awk '{print $2}')

  echo "$projectname"
  echo "$projectId"

# response
# project-names
Netbank734113
Netbank734112

# there respective Ids
8a70803f8045722601804f62d54c5d9d
8a70801c804568ae01804f625a923f8d

I need a project-id for doing some operation. I'm using the below for-loop for it.

count=0
for i ${projectId}
 do

   count=`expr $count + 1`  
   echo "Project-ID: ${i} count: ${count}"
   echo " "  
   sleep 2
 done

I wanna use/print project names with their associated project ids in that for-loop during script execution, just to identify the name of the project script is working on. Something like the below response

ProjectName: Netbank734113 Project-ID: 8a70803f8045722601804f62d54c5d9d 1
ProjectName: Netbank734112 Project-ID: 8a70801c804568ae01804f625a923f8d 2

I don't think nested for-loop will help in my case.

So, is there a way in shell script with which I can achieve the above use case?

devops-admin
  • 1,447
  • 1
  • 15
  • 26

1 Answers1

1

Instead of splitting the value into columns, use a while-read loop:

jq ... | while read -r name id; do
    echo "ProjectName: $name Project-ID: $id"
done

Or, if you're doing more than just echo-ing the output

while read -r name id; do
    echo "ProjectName: $name Project-ID: $id"
done < <(
    jq ...
)

Or, piping into awk would be a little shorter:

jq ... | awk '{print "ProjectName:", $1, "Project-ID:", $2}'

Or, just format the output in

echo '
  [
      {"name": "Netbank734113", "id": "8a70803f8045722601804f62d54c5d9d"},
      {"name": "Netbank734112", "id": "8a70801c804568ae01804f625a923f8d"}
  ]
' | jq -r '.[] | "ProjectName: \(.name) Project-ID: \(.id)"'
ProjectName: Netbank734113 Project-ID: 8a70803f8045722601804f62d54c5d9d
ProjectName: Netbank734112 Project-ID: 8a70801c804568ae01804f625a923f8d
glenn jackman
  • 238,783
  • 38
  • 220
  • 352