vjwilson
vjwilson

Reputation: 833

Failed to echo values of variable inside "for loop"

I was writing up a bash script to collect hardware information of each servers. But at some portion of the script I am unable to print values of variable that is given multiple times in a single echo command

#!/bin/bash
NO=$(df -hT | grep ext | wc -l)
for i in $(seq 1 $NO);do export PART$i=$(df -hT | grep ext | head -$i | tail -1 | awk '{print $1}'); done
echo "Total $NO ext partitions found"
for i in $(seq 1 $NO);do echo "Ext Partition$i is ${PART$i} ";done

In my system, I have two ext partitions, so variable $NO would store value 2.

The output I expect and wanted is as follows:

Total 2 ext partitions found
Ext Partition1 is /dev/sda7 
Ext Partition2 is /dev/sda8

But I am having trouble printing "$PART$i" as expected. Right now I am getting error for "for loop" in last line.

# /root/disk.sh
Total 2 ext partitions found
/root/disk.sh: line 5: Ext Partition$i is ${PART$i} : bad substitution

Can you tell me how to correctly invoke and echo the value of PART1 and PART2 in last for loop?.

Upvotes: 0

Views: 2016

Answers (3)

Kurt Stutsman
Kurt Stutsman

Reputation: 4034

I would suggest using an array variable instead:

#!/bin/bash
NO=$(df -hT | grep ext | wc -l)
declare -a PART
for i in $(seq 1 $NO);do PART[$i]=$(df -hT | grep ext | head -$i | tail -1 | awk '{print $1}'); done
echo "Total $NO ext partitions found"
for i in $(seq 1 $NO);do echo "Ext Partion$i is ${PART[$i]} ";done

You could further simplify this code as:

PART=( $(df -hT | awk '/ext/ { print $1 }') )
NO=${#PART[@]}
echo "Total $NO ext partitions found"
for i in ${!PART[@]}; do echo "Ext Partion$i is ${PART[$i]} "; done

Note that the simplification does change the indexing to be 0-based indexing.

Upvotes: 3

rob mayoff
rob mayoff

Reputation: 385570

You need to use indirect expansion:

v=PART$i
echo "Ext Partition$i is ${!v}"

From the bash manual:

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

Upvotes: 2

IT_User
IT_User

Reputation: 779

You are trying to call ${PART$i} which is two separate variables. Try:

echo "Ext Partition$i is ${PART}${i}"

Upvotes: -1

Related Questions