I have this problem I need to solve. I barely use any Linux at work other than modify my rights on the AWS terminal so my knowledge is not great.I also have looked for quite a while and everything I have found that I thought might work has not. I am using Ubuntu and create a simple shell script and running it with bash.
Is there a way to get user integer input from read, but then use each number separately in a for loop? For instance if I had the command read and they entered 3 4 45 5 separated by spaces only could i then loop through each one individually and add them all to a sum?
How about using a file in the same loop? If I have file.txt that holds the same values on a single line 3 4 45 5, can I loop through those to do the same function of adding them together?
What is the proper format for using variables in the for loop? Is below correct? I am seeing many different ways.
#this is what I was trying
read var
sum = 0 #even the sum doesn't seem to work I dont see a different way to declare a number though
for i in '${var[0]}'
do
$((sum += i)) #confused here also have seen ('$sum' += '$i')
done
echo '$sum'
Similarly this is what I am trying to do with the file but I am using the file in place of the variable
files = "/Documents/numbers.txt"
for i in $files
Sorry if this is ridiculously simple but I am brand new for the most other than basic stuff a few years back in school.
how do i do abc123?
, notcan i do abc123?
– jsotola Jul 01 '20 at 03:25read
without flags doesn't put the values in an array, so you can't use array syntax like${var[0]}
. Single quotes prevent variable expansion, so you shouldn't use them here. – Mikel Jul 01 '20 at 04:00