Bash – Splitting bash command line argument

bashshell-scriptstring

Is this the best way to split up a colon separated bash command line argument?

#!/bin/bash
hostlist=`echo $1| awk '{split($0,Ip,":")} END{for (var in Ip) print Ip[var];}'`
for host in $hostlist
 do
  ....
 done

Best Answer

Another way would be to use IFS, the shell's built-in method to split strings into fields.

OLDIFS=$IFS
IFS=':'
set -f
for host in $hostlist; do
  set +f
  echo "$host"
done
set +f
IFS=$OLDIFS

set -f turns off filename generation (globbing): without it, wildcards *?\[ would be expanded in each word.

Related Question