3

I am trying to write something like following

for i in {a..z} && j in {1..26}
do
echo "/dev/sd"$i"1               /disk$j                                 ext4     noatime        1 1" >> test
done

Of course this is not correct syntax. Can someone please help me with correct syntax for doing this?

2
  • Unclear what you want to achieve. Do i and j move in "lockstep" with each other (i.e., a and 1, then b and 2, etc) so that you have 26 options, or are they independent giving you 26x26 options? Commented Sep 12, 2013 at 19:57
  • 1
    This question was asked before: stackoverflow.com/questions/11215088/… Commented Sep 12, 2013 at 20:02

2 Answers 2

6

To be generic, you can use 'length' as shown below.

#!/bin/bash

# Define the arrays
array1=("a" "b" "c" "d")
array2=("w" "x" "y" "z")

# get the length of the arrays
length=${#array1[@]}
# do the loop
for ((i=0;i<=$length;i++)); do
        echo -e "${array1[$i]} : ${array2[$i]}"
done

You can also assign the array like the following

array1=`awk -F" " '$1 == "CLIENT" { print $2 }' clientserver.lst`
Sign up to request clarification or add additional context in comments.

1 Comment

Since I am not allowed to perform a 1-character edit, please fix the for loop. You should use < instead of <=. Other than that, I find this answer the best one, thanks for your help!
3

You can use arrays for that:

A=({a..z}) B=({1..26})
for (( I = 0; I < 26; ++I )); do
    echo "/dev/sd${A[I]}               /disk${B[I]}                                 ext4     noatime        1 1" >> test
done

Example output:

/dev/sda               /disk1                                 ext4     noatime        1 1
...
/dev/sdz               /disk26                                 ext4     noatime        1 1

Update:

As suggested you could just use the index for values of B:

A=('' {a..z})
for (( I = 1; I <= 26; ++I )); do
        echo "/dev/sd${A[I]}               /disk${I}                                 ext4     noatime        1 1" >> test
    done

Also you could do some formatting with printf to get a better output, and cleaner code:

A=('' {a..z})
for (( I = 1; I <= 26; ++I )); do
    printf "%s%20s%15s%15s%4s%2s\n" "/dev/sd${A[I]}" "/disk${I}" ext4 noatime 1 1 >> test
done

Also, if you don't intend to append data to file, but only write once every generated set of lines, just make redirection by block instead:

A=('' {a..z})
for (( I = 1; I <= 26; ++I )); do
    printf "%s%20s%15s%15s%4s%2s\n" "/dev/sd${A[I]}" "/disk${I}" ext4 noatime 1 1
done > test

3 Comments

You don't really need B, since ${B[I]} == I.
@chepner Index starts from 0 actually but I can make an update based from that thanks.
Oh, wait, I meant to say ${B[I]} == I+1! Good catch :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.