ajsdg
ajsdg

Reputation: 53

Bash script - Pass different arguments

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.

Upvotes: 1

Views: 95

Answers (3)

cthomaspdx
cthomaspdx

Reputation: 675

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

Upvotes: 0

janos
janos

Reputation: 124804

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

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64308

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

~

Upvotes: 2

Related Questions