Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
    
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 '12 at 20:57
    
Yes I like simple, did think my solution was "over engineered" :) –  Alastair May 31 '12 at 7:05
add comment

2 Answers

up vote 7 down vote accepted

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.

share|improve this answer
add comment

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
share|improve this answer
    
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. –  Gilles May 30 '12 at 23:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.