I have the following code in an .sh file:
for num in {1..10} do echo $num done
Which should print numbers from 1 to 10. But, this is what I get:
{1..10}
Also, using C-like sytax doesn't work either:
for ((i=1; i<=10; i++))
This gets me an error:
Syntax error: Bad for loop variable
The version of bash that I have is 4.2.25.
You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.
$( command ) or. ` command ` Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.
$1, $2, $3 etc. represent the first, second, third, etc. arguments to the script. $# represents the number of arguments. $* represents the string of arguments.
The seq command generates a number sequence. Parse the sequence in the Bash script for loop as a command to generate a list. The output prints each element generated by the seq command. The seq command is a historical command and not a recommended way to generate a sequence.
The code should be as follows (note the shebang says bash
, not sh
):
#!/bin/bash echo "Bash version ${BASH_VERSION}..." for i in {0..10..1} do echo "Welcome $i times" done
source http://www.cyberciti.biz/faq/bash-for-loop/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With