0

I am trying to run the below logic in a bash script

  for i in {1..30}:
  do
  printf $i 
  if (( $i!=30 )); then
    printf ","
  fi
  done

After hours of google searching, I found that in an if condition, square brackets [ ] are used for string comparisons and circular brackets are used for arithmetic operations (( )). I also found that -ne is used for string and != has to be used for arithmetic operations.

Inspite of my best efforts, I am unable to successfully run this simple logic where I need to run the loop 30 times and print the output with commas but skip the comma in last iteration.

2
  • You mean like this? for i in {1..30}; do printf $i ; if [ "$i" != "30" ]; then printf ","; fi; done Commented Nov 16, 2018 at 20:24
  • -ne etc are not used for string comparisons. Inside [ ] or [[ ]], you use -eq, -ne, etc for numeric comparisons and = (note: just one equal sign, although bash allows two), !=, etc for string comparisons. In arithmetic contexts like (( )), you use == (note: double-equal), !=, etc for numeric comparisons, = for assignment, and there are no string operators. In other words: the operators change completely depending on context. Commented Nov 16, 2018 at 23:45

1 Answer 1

1

You can simply remove the colon : after the curly braces in the first line:

for i in {1..30}
do
  printf $i 
  if (( $i!=30 )); then
    printf ","
  fi
done

This prints what you want:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. some of the examples I saw used colon for a for loop so I used it.
Were you looking at Python examples? I can't imagine why any shell examples would use a colon. (Or did you really see a semicolon (;)? One would be required if do were on the same line as for, but would be optional otherwise.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.