4

I am trying to understand the output of this command- echo ?. The output I see is a single | charcter.

  • What is the output of echo ? in your system?? – Abhik Bose Dec 29 '17 at 16:35
  • I edited my quetsion and changed my command echo abc? to simply echo ? – Ravi Kumar Dec 29 '17 at 16:36
  • @RaviKumar: The behavior is still the same. It would still return a file/directory with a single character name. Try echo ?? for 2 length file names – Inian Dec 29 '17 at 16:41
  • If you do not want this to happen and do not want to turn off globbing, quote the ?, as in echo '?' or echo \?. – PJTraill Dec 29 '17 at 19:16
11

Because ? is a special wildcard character for the shell. $abc is not present, so it's expanded to an empty string, and ? is replaced by any one-character file or directory existing in the current directory. So, there probably is a file/directory named | in your current directory.

On my system, the output is different:

$ echo $abc?
_ 1

If there's no one-character file/directory, the ? comes out unexpanded.

And, indeed, there are directories _ and 1.

  • 1
    @AbhikBose: So, there's no one-character file/directory. – choroba Dec 29 '17 at 16:34
  • 5
    @GeorgeUdosen then you have a file/dir called ~ in your home. As choroba explained, echo ? basically means "print the list of filenames in the current directory that match the glob ?". The glob ? matches any single character, so that's what's printed. – terdon Dec 29 '17 at 16:36
  • 3
    I guess you created it with ... > | ... when wrongly combining redirection with pipe (I often find files named | or { all over the place). – choroba Dec 29 '17 at 16:46
  • 1
    On zsh in case of no one character filename the output is zsh: no matches found: ?. – jimmij Dec 29 '17 at 16:58
  • 1
    @jimmij: You can get similar behaviour in bash with shopt -s failglob. – choroba Dec 29 '17 at 17:03
1

Because the ? is split into a word and it contains a glob character (?) that basically says:

Print the list of filenames in the current directory that match the glob ?.

The glob ? match any file with a single character. So, this works:

$ touch a \| b
$ echo ?
| a b
$ ls -l ?
-rw-r--r-- 1 user user 0 Dec 29 10:03 '|'
-rw-r--r-- 1 user user 0 Dec 29 10:03  a
-rw-r--r-- 1 user user 0 Dec 29 10:03  b

If there is no file/directory with one character, this happens:

$ rm a \| b
…
$ echo ?
?

That is the output in bash with default settings.
To clearly see the files do:

$ ls -l ?
ls: cannot access '?': No such file or directory

If nullglob is activated, no output will be printed

$ shopt -s nullglob
$ echo ?
$

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.