Demontager
Demontager

Reputation: 227

Shift commands within bash script

I need a way to execute same command inside "for" loop, e.g. command 1. Indeed i need this, because command 1 is very long and should be executed similar for deferent variables.

if [ $variable = 'all' ]; then  
  for host in "${servers[@]}"; do   
command 1
  done
elif [ $variable != 'all' ]; then
--->go to command 1
fi

Upvotes: 0

Views: 74

Answers (2)

glenn jackman
glenn jackman

Reputation: 246942

This is what functions are for: code re-use

do_command1() {
    local host=$1
    command1 "$host" arg ...
}

if [ $variable = 'all' ]; then  
    for host in "${servers[@]}"; do   
        do_command1 "$host"
    done
else 
    do_command1 def_host
fi

Upvotes: 2

chepner
chepner

Reputation: 531480

Create a common array to iterate over, setting its value based on $variable:

if [[ $variable = 'all' ]]; then
    my_arr=( "${servers[@]}" )
else
    # You may need to provide a suitable value for the lone
    # array element here, other than "dummy_host"
    my_arr=( dummy_host )
fi

for host in "${my_arr[@]}"; do
    command 1
done

Upvotes: 1

Related Questions