Array Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Stang02GT
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    Array Question

    I am learning some basic programming in linux ( Fedora 5). I am just creating some simple programs and I am wondering if anyone can help me figure this out.

    I have this array....

    Code:
    let i=1
    for array3 in "$@"
    do
    names[i]="$array3"
    let i=i+1
    done
    for i in "${names[@]}"
    do
    echo $i
    done
    How can i change this script to have the data read from within the program rather then from the command line?


    thank you in advance for any help!
  • radoulov
    New Member
    • Jun 2007
    • 34

    #2
    Assuming recent version of bash (as you said FC5)
    and a file in the following format:

    Code:
    entry1
    entry2
    entry3
    You can change the code like this:

    Code:
    while IFS= read -r; do
    	names[((++i))]="$REPLY"
    done<your_file_here
    
    for i in "${names[@]}"; do
    	printf "%s\n" "$i"
    done
    
    # or just: printf "%s\n" "${names[@]}"

    Comment

    • Stang02GT
      Recognized Expert Top Contributor
      • Jun 2007
      • 1206

      #3
      Thank you very much!!


      Is there anyway you could help me understand what you did a little better?

      Comment

      • radoulov
        New Member
        • Jun 2007
        • 34

        #4
        Originally posted by Stang02GT
        Is there anyway you could help me understand what you did a little better?
        First off I have to correct my own post (++i is sufficient, you don't need (())):
        Code:
        while IFS= read -r; do
        	names[++i]="$REPLY"
        done<your_file_here
        IFS= and read -r

        IFS= is "clearing" the internal field separator,
        otherwise leading and trailing IFS characters will
        be stripped: for example, a record like " word ... "
        becomes "word ...". The -r option for read is necessary
        to prevent some escape sequences from being expanded
        - \n will not be expanded to a new line for example
        (if that's not what you want,
        use just while read;do ...).

        names[++i]="$REPLY"

        Some recent shells like bash, ksh93 and zsh
        accept the syntax ++var and var++
        for incrementing the value of a variable.
        $REPLY is the default variable for some
        statements like read and select.

        HTH a bit.

        Comment

        Working...