1

This script has to run 4 times and change its path accordingly. But only Name changes 4 times and path remains the same. Any idea what is wrong with the script? I'm new to bash.

#!bin/bash

File=/tmp/tmp.txt
NAME=(NAME1 NAME2 NAME3 NAME4)
DIR=(/home/path1 /home/path2 /home/path3 /home/path4)

for NAME in "${NAME[@]}"
     do
             /sbin/myprogram start --read $FILE --path $DIR --name $NAME
     done;

In General, I'm trying to automate this command:

/sbin/myprogram start --read /tmp/tmp.txt --path /home/path1 --name NAME1
/sbin/myprogram start --read /tmp/tmp.txt --path /home/path2 --name NAME2
/sbin/myprogram start --read /tmp/tmp.txt --path /home/path3 --name NAME3
/sbin/myprogram start --read /tmp/tmp.txt --path /home/path4 --name NAME4

Can we modify the script to start as

for FILE in /tmp/txt

and then read NAME and Dir separately every time?

I don't want to put this directly in script because there might be more path, name and even there might be more than one txt.

janos
  • 120,954
  • 29
  • 226
  • 236
ajsdg
  • 53
  • 1
  • 5

3 Answers3

2

In your script, you are only looping over the NAME array instead of both the NAME and DIR arrays. For more details on how to loop over the arrays in parallel, you can refer to this question: Iterate over two arrays simultaneously in bash

I think a more straightforward solution in your case is to use a function:

#!/bin/sh

run () {
    /sbin/myprogram start --read /tmp/tmp.txt --path "$1" --name "$2"
}

run /home/path1 NAME1
run /home/path2 NAME2
run /home/path3 NAME3
run /home/path4 NAME4

~

Community
  • 1
  • 1
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • okay thanks. Can you also tell me how to loop both name and DIR? It might help me understand and use it for something else in future. – ajsdg Oct 03 '15 at 14:27
  • @GoldFlake129: There's already some good answers here: http://stackoverflow.com/q/17403498/951890 – Vaughn Cato Oct 03 '15 at 14:28
1

When you have 2 or more arrays of the same size, and want to do something with the corresponding indexes, you need to iterate over the indexes instead of the elements like you did.

For example, like this:

for ((i = 0; i < ${#NAME[@]}; ++i))
do
    /sbin/myprogram start --read $FILE --path ${DIR[$i]} --name ${NAME[$i]}
done

UPDATE

You mentioned in a comment that if there is an error, you would like to break out of the loop. Here's one way to do that:

for ((i = 0; i < ${#NAME[@]}; ++i))
do
    /sbin/myprogram start --read $FILE --path ${DIR[$i]} --name ${NAME[$i]} || break
done
janos
  • 120,954
  • 29
  • 226
  • 236
0

This does the same thing as the solution you marked as correct, but just a little easier to read.

File=/tmp/tmp.txt
NAME=(NAME1 NAME2 NAME3 NAME4)
DIR=(/home/path1 /home/path2 /home/path3 /home/path4)

for index in ${!NAME[*]}; do 
   /sbin/myprogram start --read $FILE --path ${DIR[$index]} --name ${NAME[$index]}
done
cthomaspdx
  • 655
  • 5
  • 6