[KSH] Creating automatic variable from read input


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting [KSH] Creating automatic variable from read input
# 1  
Old 10-07-2012
[KSH] Creating automatic variable from read input

Hello there, I am posting to seek help with a KSH script,

I am making a simple calculation program where the user can enter as many numbers as they like, I am getting their input using the read command, however I am not sure how to repeat doing this and storing the input in to new variables until the user wants the program to calculate.

Here is what I have so far

Code:
#!/bin/ksh

echo "Please input two numbers"
echo
echo "Please input value 1: "
read x1
echo
echo "Please input value 2: "
read x2

echo "The answer is: "
echo
echo "($x1 + $x2 | bc))"

I am thinking maybe using an Array is the best way to go about this, but I am really stumped on how to do this Smilie
# 2  
Old 10-07-2012
Don't take it as a solution (it's not), take it as a hint:
Code:
#!/bin/ksh

unset array
typeset -a array
while true; do
 echo "Input a number (just press ENTER to stop): "
 read input
 [[ "$input" = "" ]] && break
 array+=( "$input" )
done

echo ${array[@]}

unset sum
for ((i=0;i<${#array[@]};i++)); do
 sum=$(( $sum + ${array[$i]} ))
done

echo $sum

--
Bye
# 3  
Old 10-07-2012
I guess I'm really missing something here. Why do you believe that an array is needed here? Why not just keep a running total as you gather numbers? This is written assuming ksh, but should work for any POSIX-conforming shell (not csh and not tcsh):
Code:
#!/bin/ksh
GetNumMsg='Enter a number (ctrl-d when done): '
printf "$GetNumMsg"
sum=0
while read x
do      sum=$((sum + x))
        printf "$GetNumMsg"
done
printf "\nSum of numbers entered is: %d\n" $sum

# 4  
Old 10-08-2012
Quote:
Originally Posted by Don Cragun
Why do you believe that an array is needed here? Why not just keep a running total as you gather numbers?
I guessed he wanted flexibility.

First he collects data, then he can use (and reuse) them to calculate as many things as he needs (even easily changing his code).
--
Bye
# 5  
Old 10-08-2012
Quote:
Originally Posted by Lem
I guessed he wanted flexibility.

First he collects data, then he can use (and reuse) them to calculate as many things as he needs (even easily changing his code).
--
Bye
Hi Lem,
You suggested an array because pandapowerbox said in the 1st message in this thread:
Code:
I am thinking maybe using an Array is the best way to go about this, but I am really stumped on how to do this

My question and suggestion were directed to pandapowerbox, not to you. Your script was an excellent example of how to use an array to solve a problem like this; if an array is needed. I'm sorry for the confusion.

Pandapowerbox,
I see a lot of newbie programmers who pay too much attention to the semantics of a possible solution without stepping back to look at the bigger picture. If you start out thinking that you need to add a list of variables and print the sum, then you think about accumulating an array and adding them at the end. But, if your goal is just to get the sum of a list of values, you make the problem much more complex by assuming you need to save the input values as separate variables or as separate members of an array instead of just keeping a running sum as you read each individual value.

I also note that the last line of your starting script:
Code:
echo "($x1 + $x2 | bc))"

almost certainly doesn't do what you wanted it to do.

By passing the quoted string to echo, it expands $x1 and $x2, but doesn't invoke bc. And, if you had left off the double quotes, you also have mismatched parentheses. And, if you had used: echo ($x1 + $x2 | bc) or echo (($x1 + $x2 | bc)) you would have had ksh syntax errors. You could have used echo $($x1 + $x2 | bc) and gotten the result you were probably expecting, but if you're learning ksh, you should look at arithmetic expansion that does all of the work in the shell without needing to invoke another utility (bc in this case). Using arithmetic expansion this would simply be: echo $((x1 + x2)).

You have probably already noticed that the suggestions that Lem and I provided both use ksh's arithmetic expansions sum=$(( $sum + ${array[$i]} )) and sum=$((sum + x)), respectively, rather than invoking awk, bc, dc, expr, perl, or some other utility to perform these simple calculations.

Hopefully, the comments Lem and I have made will help you see that there are almost always several ways to do something in shell scripts and help you think about a few of the possibilities as you tackle new problems like this.
# 6  
Old 10-09-2012
Hey guys

Thanks for the detailed replies, they have really helped me a great deal!!

@Don: I decided to maybe use an Array as I wasn't aware of any other way of doing what I wanted to do using KSH ... I have only been using it for a week but I guess I have been proven wrong that I can do what I need without an Array.
# 7  
Old 10-10-2012
Ksh93, bash, ... give also little nicer syntax version for the arithmetic expansion .
You can put everything inside (( )) and use variables without dollar sign $.
This is not Posix compatible, but look easier to read. Works only in the arithmetic expansion using (( )).

In this example input values has saved to the array and to the string (inputstr).
Code:
inputstr=""
while true
do
 echo -e -n "Input a number (just press ENTER to stop): "
 read input
 [ "$input" = "" ] && break
 array+=( "$input" )              # new element to the array
 inputstr="$inputstr $input"    # join string
done

echo ${array[@]}

sum=0
# take all values from the list, in this case all values from array
for val in ${array[@]}
do
    (( sum+=val ))   # works in ksh93, bash, ...
    # sum=$(( $sum + $val ))  # posix compatible, you can use also let command
done

echo $sum

# or using inputstr
sum=0
for val in $inputstr
do
    (( sum+=val ))   
done

echo $sum

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

ksh - Read input from file and output CSV i same row

Hello I have the following output and want the output to look: FROM: GigabitEthernet0/0 is up, line protocol is up 1 input errors, 0 CRC, 0 frame, 1 overrun, 0 ignored 275 output errors, 0 collisions, 3 interface resets GigabitEthernet0/1 is up, line protocol is up 0... (4 Replies)
Discussion started by: JayJay2018
4 Replies

2. Shell Programming and Scripting

ksh to read input until QUI

Hello all I'm looking to write a simple script (ksh/sh/bsh) to read user input and write it to a file (adding each time) until the user enters QUIT at which point I'm hoping to ask some more questions. Any help much apprecited (2 Replies)
Discussion started by: Grueben
2 Replies

3. Shell Programming and Scripting

ksh loop to read input until QUIT

Hi I'm looking to write a simple ksh loop reading user input (and write it to a file) until the user enters QUIT at which point I want it to continue. Does anyone have an example of this type of loop? Any help much appreciated Cheers (2 Replies)
Discussion started by: Grueben
2 Replies

4. Shell Programming and Scripting

Read multiple input from CLI :ksh

Hi folks.. i got a requirement to red multiple directories from STDIN and store them to a variable. ex:- echo "Enter directory to add:" echo " Enter directory to add:" read value till there is input and when there is no input close the read loop and store variable into an array ... (1 Reply)
Discussion started by: bangaram
1 Replies

5. Shell Programming and Scripting

Automatic Input to a command

Hi, I have an issue where i run an command in a shell script. command >/dev/null ret=$? echo ret If the command returns an error i'm redirecting it to /dev/null. The prob is if an error comes it expects the user to press return to continue. And hence the return is not echoed. and the end... (4 Replies)
Discussion started by: subhrap.das
4 Replies

6. Shell Programming and Scripting

KSH: Compare variable to $1 in an input file

Hello, I am working with KSH on AIX and I have 2 files generated from different sources... as seen below: FILE1 FILE2 AAA AAA@ABS0001C BBB BBB@ABS0003D CCC CCC@ABS0023A DDD DDD@ABC0145D EEE EEE@ABS0090A FFF FFF@ABS0002A GGG GGG@ABC0150D HHH FILE1 is main main data source,... (4 Replies)
Discussion started by: right_coaster
4 Replies

7. Shell Programming and Scripting

make a variable read the value from the standard input

Hi, In Perl, how can we define a variable make it read the value from the standard input? Meaning, how can have the user type in the value that will be assigned to the variable? Thanks, (2 Replies)
Discussion started by: Pouchie1
2 Replies

8. UNIX for Advanced & Expert Users

Automatic input to commands

Hi, In a shell script i am running a command which is asking for input. How can i give that automatically. I have done this before but for the time being can't recall. Was something like <| Thanks (6 Replies)
Discussion started by: vibhor_agarwali
6 Replies

9. Shell Programming and Scripting

Automatic Arrays in ksh

Given a line of text in ksh: string1 string2 string3 .....stringn is there a way of automatically assigning each string to an array element? Or just different variables would do. Thanks, Jon (1 Reply)
Discussion started by: Jonny2Vests
1 Replies

10. Shell Programming and Scripting

creating a fixed length output from a variable length input

Is there a command that sets a variable length? I have a input of a variable length field but my output for that field needs to be set to 32 char. Is there such a command? I am on a sun box running ksh Thanks (2 Replies)
Discussion started by: r1500
2 Replies
Login or Register to Ask a Question