6

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
2
  • Ask yourself if the code is readable or really cryptic. I think the code is hard to understand without extra comments, so there must be a better way to code it. That being said, I like the accepted answer from Shawn :o)
    – jippie
    May 30, 2012 at 20:57
  • Yes I like simple, did think my solution was "over engineered" :)
    – Alastair
    May 31, 2012 at 7:05

2 Answers 2

8

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.

4

I think the simplest solution is just to use bash builtins:

#!/bin/bash
hostlist=${1//:/ }  # this will replace all : with a space

for host in $hostlist ; do
    echo ${host}
done

Another way (still simpler than your awk solution) is to use cut though this probably depends on GNU cut.

#!/bin/bash
hostlist=$(echo $1 | cut -d : --output-delimiter=" " -f 1-) 

for host in $hostlist ; do
    echo ${host}
done
1
  • 1
    This assumes there are no special characters (no whitespace or globbing characters) in the names. That's likely to be true in a “hostlist”, but not a general technique. May 30, 2012 at 23:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .