0

for example the second line I want to do dynamically based on length of first:

DOMAINS=("gmail.com" "yahoo.com" "yahoo.co.uk" "yahoo.co.jp")
s_domain=(0 0 0 0)
0
3

At least in recent bash versions, you can apply parameter expansions element-wise to an array:

s_domain=("${DOMAINS[@]/*/0}")

ex.

$ DOMAINS=("gmail.com" "yahoo.com" "yahoo.co.uk" "yahoo.co.jp")
$ s_domain=("${DOMAINS[@]/*/0}")
$ printf '%s\n' "${s_domain[@]}"
0
0
0
0
0

With a for loop:

for i in "${DOMAINS[@]}"; do s_domain+=(0); done
1
  • A good answer, but note that this does not guarantee that each of the indices of $s_domain match the indices of $DOMAINS, only that the total number of elements is the same. – spuck May 12 '20 at 21:04
-1

Using printf (assuming IFS is default):

$ domains=("gmail.com" "yahoo.com" "yahoo.co.uk" "yahoo.co.jp")
$ s_domain=( $(printf ' 0%.0s' $(seq "${#domains[@]}")) )
$ printf '%s ' "${s_domain[@]}"; echo
0 0 0 0

The four possible solutions in this question are:

#! /bin/bash

n=${1:-100}
domains=( $(seq "$n") )

time s_domain=("${domains[@]/*/0}"); echo "${#s_domain[@]}"
time s_domain=( $(printf ' 0%.0s' "${domains[@]}") )
unset s_domain;
time for i in "${domains[@]}"; do s_domain+=(0); done

time s_domain=( $(printf ' 0%.0s' $(seq "${#domains[@]}")) )

And the time they take using 1 Million values are:

testbash.sh 1000000
run    : 0m6.235s sec
run    : 0m6.931s sec
run    : 0m9.575s sec
run    : 0m3.921s sec

So, the option in this answer is quite faster than the other solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.