Creating a comma-separated sequence of numbers based on input in Bash

I found a few things here to help me, as I am learning to code in Bash, and they are all close, but not quite.

I need to take a positive integer input and print on one line up to one, all separated by commas, without a comma at the end of the last variable.

This is what I have so far:

#!/bin/bash #countdown read -p "Enter a Number great than 1: " counter until ((counter < 1)); do echo -n ",$counter" ((counter--)) done 

This almost works, but I can't figure out how to prevent the comma from the front and not have it behind the last variable.

EDIT: You guys are AWESOME. I poured this book and learned more in ten minutes than I did with an hour there.

So, is there some kind of command that I could use to make sure that only one number was entered and make sure that it should be positive?

Is there some way to put an if statement to read in order to provide it with <= 1 and only one character?

I only have the source code in basic C encoding, so I have the basics, but translating them to Bash is harder than expected

+4
source share
5 answers

Use seq with the -s option:

 seq -s, $counter -1 1 
+8
source

Probably just using a parenthesis extension :

 #!/bin/bash #countdown read -p "Enter a Number great than 1: " counter eval printf "%s" {${counter}..2}, 1 

Test:

 Enter a Number great than 1: 10 10,9,8,7,6,5,4,3,2,1 

To check the input, you can use regular expressions:

 #!/bin/bash #countdown read -p "Enter a Number great than 1: " counter if [[ ${counter} =~ ^[1-9][0-9]*$ ]] then eval printf "%s" {${counter}..2}, 1 fi 
+5
source

One of the methods

 read -p "Enter a Number great than 1: " counter echo -n "$counter" ((counter--)) until ((counter < 1)); do echo -n ",$counter" ((counter--)) done 
+2
source

A slightly inconvenient array design, the seq command and the subshell to localize changing the IFS parameter will work.

 read -p "Enter a Number great than 1: " counter range=( $(seq $counter -1 1) ) ( IFS=,; echo "${range[*]}" ) 
+1
source

Here is another way ... influenced by the chepner solution , but not using seq :

The contents of script.sh:

 #!/bin/bash read -p "Enter a Number great than 1: " counter range=( $(eval echo {$counter..1}) ) ( IFS=,; echo "${range[*]}" ) 

Test:

 $ bash script.sh Enter a Number great than 1: 5 5,4,3,2,1 $ bash script.sh Enter a Number great than 1: 30 30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1 
+1
source

Source: https://habr.com/ru/post/1485716/


All Articles