By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,421 Members | 1,233 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,421 IT Pros & Developers. It's quick & easy.

Array Question

Stang02GT
Expert 100+
P: 1,208
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....

Expand|Select|Wrap|Line Numbers
  1. let i=1
  2. for array3 in "$@"
  3. do
  4. names[i]="$array3"
  5. let i=i+1
  6. done
  7. for i in "${names[@]}"
  8. do
  9. echo $i
  10. 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!
Oct 30 '07 #1
Share this Question
Share on Google+
3 Replies

radoulov
P: 34
Assuming recent version of bash (as you said FC5)
and a file in the following format:

Expand|Select|Wrap|Line Numbers
  1. entry1
  2. entry2
  3. entry3
  4.  
You can change the code like this:

Expand|Select|Wrap|Line Numbers
  1. while IFS= read -r; do
  2.     names[((++i))]="$REPLY"
  3. done<your_file_here
  4.  
  5. for i in "${names[@]}"; do
  6.     printf "%s\n" "$i"
  7. done
  8.  
  9. # or just: printf "%s\n" "${names[@]}"
Nov 4 '07 #2

Stang02GT
Expert 100+
P: 1,208
Thank you very much!!


Is there anyway you could help me understand what you did a little better?
Nov 5 '07 #3

radoulov
P: 34
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 (())):
Expand|Select|Wrap|Line Numbers
  1. while IFS= read -r; do
  2.     names[++i]="$REPLY"
  3. 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.
Nov 6 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.