0

In the following shell script, I use two arrays to store the numbers in p1.txt and p2.txt and then display them.

cat p1.txt | awk '{for(i=1;i<NF;i++) {party1[$i-1]=$i}}'
cat p2.txt | awk '{for(j=1;j<NF;j++) {party2[$j-1]=$j}}'
for ((k=1;k<10;k++))
do
    echo "${party1[$k]}"
    echo "${party2[$k]}"
done

However, when I run it with the default sh, it says Syntax error: Bad for loop variable; when I run it with bash, no numbers can be displayed. What's wrong with the script?

3
  • POSIX sh doens't support for (( ... )); do. Use bash. Commented Dec 5, 2016 at 14:45
  • I use bash but can see no numbers displayed.. Commented Dec 5, 2016 at 14:50
  • For the array part there is already a brilliant answer covering that. Commented Dec 5, 2016 at 14:51

1 Answer 1

1

you can use this

#!/bin/bash
IFS=' ' read -r -a party1 <<< $(cat p1.txt)
IFS=' ' read -r -a party2 <<< $(cat p2.txt)

for ((k=1;k<10;k++))
do
    echo "${party1[$k]}"
    echo "${party2[$k]}"
done
Sign up to request clarification or add additional context in comments.

5 Comments

Thx. I tried this but still no numbers can be displayed.
@haik, I updaded ans. maybe this can help you
for what it's worth, both the read and mapfile versions work on my computer running wsl.
@MustafaDOGRU It really works. I'm so grateful for your help.
@andlrc When I replace the start index k=1 with k=0, the whole array is displayed no matter what the terminating condition is.

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.