I’m trying to do a seemingly easy thing: a script that takes a variable from the command line ($1) and uses this as the length of the for loop. So if the command is run.sh in terminal:
run.sh 5
will run the for loop 5 times. This is my attempt:
#!/bin/sh
for i in {1..$1};do
echo $i
done
But the only output I receive is:
{1..5}
How can I solve this?
Note: I’m a total beginner in bash/shell scripting.
are you really using the bash shell. Not all shells (especially the true /bin/sh (bourne) ) support that feature. To disambiguate your situation, use
at the top of your script.
One solution is to use
evalsays, “for the current command string, in this caseecho ${1..$1}, don’t execute the command yet, re-evaluate the complete command line for any expandable variables.”If you system has the
seqcmd, then you can rewrite this asseqis short for sequence, and can take any starting and ending number, and an optional ‘skip by’ factor, saseq 0 5 100will count by 5’s to 100.I hope this helps.