I have a small bash script that doesn't work the way I want
here is the code
#! /bin/bash
echo "Escriba la cantidad de letras"
read x
for i in $x;do
echo "Letra $i"
read y
echo $y
done
#export Mensaje
#./recibir.sh
Image of the logical error
It is supposed to repeat the echo for me the number of times I enter the top echo, but it only does it once and I don't understand the logic of bash for very well
The
for
bash one iterates over a set of values ; is similar tofor ... in
or toforeach
other languages.It looks better with an example:
Bash creates a sequence containing all the files that match the pattern.
[ file1.sh file2.sh file3.sh ]
for
iterates over the elements of the generated sequence.idx = file1.sh -> ...
idx = file2.sh -> ...
For
for
numerics, you should doTo complement @Trauma's answer.
"for" does a little more than iterate over a set of values, or rather, that set of values is generated and then iterated over, also operating under premises, just as it would in c, and it does so in several ways:
for name in < secuencia separada por espacios >;do lista de comandos;done
for ((expr1;expr2;expr3));do lista de comandos;done
This can be found at
man 1 bash
.I mention this because after in, in example 1, the for loop works on expansions, that is:
They are equivalent but they work with different types of expansions, the first was on pathname expansion and the second was on command substitution, but it can also be done on brace expansion, that is:
Or a slightly more complex example in which you can combine them:
It will print all the files that end with foo and that are inside the sc2 and sc3 folders that are inside the ca1 folder.
You can also see the expansions in
man bash
, in the EXPANSIONS section. It is important to note that the order in which the strings are expanded has an order of precedence.I say this about the expansions because I think it is necessary to clarify it since there are issues like these:
In the second example @Allex put up, you can see that you can also iterate over brace expansion over an array.
If what you want is to make a typical for from 0 to x where x is read from a variable and represents the repetition limit, you can use the for with syntax very similar to the C language.
On the other hand, bash supports the foreach in the same for structure, the foreach is very useful for reading arrays, I leave you a practical example:
"${r[@]}"