Results 1 to 3 of 3

Thread: Iterate bash script over a list

  1. #1
    Join Date
    Dec 2010
    Beans
    98

    Iterate bash script over a list

    I am setting up to use ansible, need to set up ssh keys on numerous servers to receive playbooks (updates and scripts) using a key instead of a password to initiate the ssh session. I've written a bash script that copies the public key into the destination server, and it works well, once that is done I am able to ssh in without a password. I'd like to write into the script that it executes this on numerous IP's (which are not consecutive). Any suggestions on how to set that up? Here's psuedo code for what I'm trying to do:

    List of IP addresses:
    IP1
    IP2
    IP3
    ...
    IP500

    bash script:
    x=1
    for IPx:
    do foo
    when done
    x=x+1
    go back to for IPx line
    If x not on list (all IP addresses done)
    exit

    regards, Richard

  2. #2
    Join Date
    Mar 2010
    Location
    Squidbilly-Land
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: Iterate bash script over a list

    Loops ... an example.

    Code:
    #!/bin/sh
    #
    # This is for really simple XVID conversion, use
    #
    for filename in "$@"; do
      DO SOMETHING with $filename .... 
    done
    So - if you pass in a list of IPs, space-separated ...

    OTOH, why not use ansible to push the keys? That's how I do it.
    Code:
    action: lineinfile dest=/home/{userid}/.ssh/authorized_keys

  3. #3
    Join Date
    Jul 2007
    Location
    Poland
    Beans
    4,499
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Iterate bash script over a list

    arrays (lists) go like this:

    Code:
    #!/bin/bash
    
    ip_list=( 1.1.1.1. 2.2.2.2
              3.3.3.3  4.4.4.4
              etc etc )
    
    for ip in "${ip_list[@]}"
    do
        echo "$ip"
    done
    you could also read the list from the file.

    Code:
    #!/bin/bash
    
    while read ip
    do
        echo "$ip"
    done < ip_list.txt
    if your question is answered, mark the thread as [SOLVED]. Thx.
    To post code or command output, use [code] tags.
    Check your bash script here // BashFAQ // BashPitfalls

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •