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)
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityfor 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)
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
With a for loop:
for i in "${DOMAINS[@]}"; do s_domain+=(0); done
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.