21

Please explain why 1 4 5 6 is displayed for the last four echo statements? I hit this by accident once, but I am now curious as to why this behavior occurs.

These statements work as expected (for me).

$ echo [ 9876543210 ]  
[ 9876543210 ]

$ echo [237890]  
[237890]

These echo statements consistently display 1 4 5 6. Is there something special about these numbers?

$ echo [9876543210]  
1 4 5 6

$ echo [abcd9876543210ghi]  
1 4 5 6

$ echo [-123456-]  
1 4 5 6

$ echo [-7654321-]  
1 4 5 6

Thanks!

  • The possible duplicate is related and helpful, but not a duplicate. The possible duplicate is from the perspective of an rm command. This question is from the perspective of a perceived "weird behavior" of an echo command. The underlying answer for both is globbing. Someone searching for issues with an echo command would not easily find the rm question, but would more likely land here.
3
  • 16
    you have 4 files in your current directory, named: 1 4 5 and 6
    – Jeff Schaller
    Commented Feb 27, 2017 at 18:49
  • 1
    Note that if you turn on nullglob, your second example (echo [237890]) will actually print nothing, which could have been a clue that you were seeing glob-expansion in the other examples. Commented Feb 28, 2017 at 0:46
  • 3
    Possible duplicate of Working of rm/ls with [0-9]
    – muru
    Commented Feb 28, 2017 at 5:11

1 Answer 1

35

The open bracket [ is a special character to the shell; it opens up a pattern matching algorithm that says "match any of the characters inside the brackets". Because you have 4 files named as: 1, 4, 5, and 6 in your current directory, when the characters inside the brackets contain any of those digits, your shell replaces the pattern-match with those filenames. When you instead use echo [ 9876543210 ] you are calling echo with 3 parameters: [, 9876543210, and ].

You should quote your echo statement's parameters to prevent the shell from seeing it as a pattern matching request.

$ echo '[9876543210]'
[9876543210]

(or remove the files named 1, 4, 5, and 6 -- but that's a workaround to demonstrate the behavior, not a fix).

1
  • The key point is that the argument to echo is interpreted differently by bash depending on whether or not there are spaces between the square brackets and what's inside them. [123] vs. [ 123 ].
    – jskroch
    Commented Mar 14, 2017 at 15:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .