-1

I am trying to get these strings as output for items other than zero:

[21-40]
[41-60]
[61-80]
[81-100]

But the following script is somehow trying to evaluate the contents of the _FILENAME variable.

#!/bin/bash
for i in 0 21 41 61 81
do
    if (( $i > 0 ))
    then
        _FILENAME="[$i-$((i+19))]"
    else
        _FILENAME="First File"
    fi
    echo $_FILENAME
done

I'm sure I'm missing some syntax here.

Andrew
  • 397
cenk
  • 101

2 Answers2

4

Use double-quotes around variable references, like $_FILENAME. Without double-quotes, the shell will attempt to split the variable's contents into multiple "words", and also expand any file globs (wildcard expressions) it finds. expressions like [21-40] are globs (this one matches any files named "2", "1" through "4", or "0"). If you happen to have files by any matching names in the current directory, the list of files will be printed instead of the bracket expression. Thus, all you need to do is use:

echo "$_FILENAME"

instead of the unquoted version. BTW, it's also best to use lowercase (or mixed case) for shell variable names, to avoid conflicts with the many magic variables that have special meaning to the shell or other programs.

2

Gordon has properly described the issues with your code in his answer. I'm giving you an alternative version of your code, the way I would have written it:

echo 'First file'

for (( i = 20; i < 100; i += 20 )); do
    printf '[%d-%d]\n' "$(( i + 1 ))" "$(( i + 20 ))"
done

Using printf is generally safer for outputting user-supplied or variable data. See e.g. Why is printf better than echo?

Since the intervals are regular, a C-style for loop may possibly be better suited than explicitly listing each and every interval start number.

Kusalananda
  • 333,661
  • this is great. I was trying to debug it with echo, thank you for the printf recommendation! And I should definitely use the more elegant for loop. – cenk May 30 '17 at 15:07