i have bash script which do some function with website domains like following
#!/usr/bin/env bash
domain="$1";
function A(){
ping $domain -c 4
}
function B(){
host $domain
}
A;
B;
and when i run this script by doing ./script.sh whateverdomain.com it works well.
BUT i heard that with array i can run the script against some of domains seperated by comma for example.
like ./script.sh domain1.com,domain2.com and it will excute the whole script function against the first one then the second one and i tried the following code.
my_arr=($(echo $DOMAIN | tr "," "\n"))
d=$(for domain in "${my_arr[@]}" ;
do echo $domain
done)
pingme(){
ping -c 4 $d
}
but it hanging and not passing each domain to variable $d
so i need to define array as function and when i run the script it pass domain and execute the script functions then repeat the whole script against the second domain and so on like.
#!/usr/bin/env bash
domain="$1";
function myarray(){
# the array function which will pass the domains one by one
}
function A(){
ping $domain -c 4
}
function B(){
host $domain
}
myarray;
A;
B;
./script.sh domain1.com domain2.comand iterate over the elements of"$@"in the script:for domain in "$@"; do …; done. That is the natural way to write shell scripts. Also pass the domain explicitly to the function — global variables are problematic. If you must use the comma-separated argument, then use:for domain in "${my_arr[@]}"; do pingme $domain; done— and the functions should process$1, not a global variable. Inside a function,$1is the argument passed to the function, not to the script as a whole.functionkeyword).my_arr=($(echo $DOMAIN | tr "," "\n"))is the only place I see$DOMAINcapitalized.