Reputation: 13
I have a shell script in Linux, which needs as input one argument, which can contains a list of ip adresses. These list needs to be written line by line to a file.
./myTestScript.sh 192.168.100.2,192.168.100.3
In the script, the output to be generated is
192.168.100.2 OK
192.168.100.3 OK
and written to a file called exceptions.map.
MY idea for a single IP works, but how to implement a loop ovre a list from arguments.
#!/bin/sh
IPADRESSES=$1
echo $IPADRESSES
sudo rm /appli/myApp/apps/mainApp/maintenance/exceptions.map
echo $IPADRESSES OK > "/appli/myApp/apps/mainApp/maintenance/exceptions.map"
Upvotes: 1
Views: 50
Reputation: 6134
One command, no loop needed:
$ printf '%s OK\n' ${1//,/ } > "/appli/myApp/apps/mainApp/maintenance/exceptions.map"
${1//,/ }
splits your command argument by replacing all commas with spaces. printf
prints each IP according to your format.
${1//,/ }
can also be used in a loop:
for ip in ${1//,/ }; do something with "$ip"; done
Upvotes: 1
Reputation: 17041
Here's a pure-bash way:
#!/bin/bash
IFS=, read -ra addresses <<<"$1"
for addr in "${addresses[@]}"; do
echo "$addr OK"
done > exceptions.map
The IFS=...
line reads the comma-separated contents of the first argument $1
into array addresses
. They are comma-separated because of IFS=,
. The for
loop then prints each address in turn, plus the OK.
Upvotes: 0
Reputation: 212208
#!/bin/sh
echo "$1" | tr , \\n | sed 's/$/ OK/' > exceptions.map
Or, if you really want to write a loop:
IFS=,
for i in $1; do
echo "$i OK"
done
Note that the $1
here must remain unquoted, since we are explicitly relying on word-splitting. But usually, I would change the API a bit and have the caller pass each IP as a separate arugment and do for x; do echo "$x OK"; done
.
Upvotes: 1