Bash – Why Does echo [9876543210] Display 1 4 5 6?

bashechopatternsshellwildcards

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.

Best Answer

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

Related Question