bash script. run command with counted numbers and

2019-09-14 07:55发布

问题:

This question already has an answer here:

  • How do I iterate over a range of numbers defined by variables in Bash? 20 answers

i try to code a script. it ask me how many "anything" you want? and i answered with a number like 10

#!/bin/bash
echo -n "Please enter some input: "
read input

now I like perform a command 10 times include numbers from 001 to 010 for example i get the right numbers with:

seq -f "%03g" 1 $input

but how can I execute now commands using this number like:

command anyname-001 -some -parameter
command anyname-002 -some -parameter
command anyname-003 -some -parameter

....

thanx for help

回答1:

Just use a for loop over the range. That should do the trick.

#!/bin/bash
echo -n "Please enter some input: "
read input

for number in `seq -f "%03g" 1 $input`
do
  command anyname-${number} -some -parameter
done


回答2:

One line (well, formally two):

#!/bin/bash
printf 'command anyname-%03d -some -parameter\n' $(seq $1)

Call the script as:

$ script 10
command anyname-001 -some -parameter
command anyname-002 -some -parameter
command anyname-003 -some -parameter
command anyname-004 -some -parameter
command anyname-005 -some -parameter
command anyname-006 -some -parameter
command anyname-007 -some -parameter
command anyname-008 -some -parameter
command anyname-009 -some -parameter
command anyname-010 -some -parameter


回答3:

With GNU bash:

for ((i=1;i<=$input;i++)); do
  printf -v number "%03d" "$i"
  echo command anyname-${number} -some -parameter
done

If everything looks okay, remove echo.



标签: linux bash shell