1

I need to separate the input into different values after reading it from command line. I am reading it using the OPTARGS method along with while loop. So my input will be like "hostanme1 hostname2 hostnamen"

How can I loop in through this to extract the hostnames in separate variables.

    while getopts S:H: opt
do
   case ${opt} in
      S)
        SCHNAME=${OPTARG}
      ;;
      H)
        HOST=${OPTARG}
      ;;
      *)
        DisplayUsage
        exit 1
      ;;
   esac
done

This will be run like ./filename.ksh -S schema -H "Host1 host2 host3 host4

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Preeti Maurya
  • 431
  • 1
  • 7
  • 17

1 Answers1

2

The key is to add '(' and ')' around a string with spaces between items to make an array of objects.

  H)
    HOSTS=(${OPTARG})
  ;;

for host in "${HOSTS[@]}"
do
  echo "$host"
done
GoinOff
  • 1,792
  • 1
  • 18
  • 37
  • It just took the first value from the options provided. I want all of them.. I will give the hosts in double quotes while executing – Preeti Maurya Nov 01 '17 at 14:36
  • 1
    That should be `for host in "${HOSTS[@]}"; do` – ghoti Nov 01 '17 at 14:38
  • 1
    You should use quotes, per my previous comment. Otherwise, an array element containing a space will be treated as two elements. Probably not an issue with a list of hostnames, but it's still way better to keep a standard style to your code and maintain good habits. – ghoti Nov 01 '17 at 14:39
  • @GoinOff curious to know how the for loop works. Seeing this for the first time. Newbie – Preeti Maurya Nov 01 '17 at 14:44
  • 1
    @Preeti here is a good post on the subject https://stackoverflow.com/questions/1878882/arrays-in-unix-shell – GoinOff Nov 01 '17 at 14:46
  • individual items in a bash array can be accessed in the following way: `${HOSTS[0]}` for first element, `${HOSTS[1]}` for seconds element – GoinOff Nov 01 '17 at 14:48
  • thats a great article. Thank you @GoinOff – Preeti Maurya Nov 01 '17 at 14:48