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


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

for i in 0 21 41 61 81
    if (( $i > 0 ))
        _FILENAME="First File"
    echo $_FILENAME

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

  • I couldn't reproduce what you described; but you may try to run it with bash -x – Andrew Miloradovsky May 30 '17 at 1:08
  • 1
    I get the expected output: – fpmurphy May 30 '17 at 2:49

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.

  • Thanks Gordon. "Echo" was me trying to debug this. Now I know, thanks to you. – cenk May 30 '17 at 15:04

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 ))"

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.

  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.