0

I have been looking for this question everywhere, but I didn't find it and there doesn't seem to be any kind of answer yet to my current problem, which, frankly, doesn't even make sense.

So, what I want to do is escape the question mark ? in my variable declaration. Obviously writing

var=?

won't do it. Of course, you would then use backslash along with the question mark to solve the problem, usually:

var=\?

However: This doesn't work (but it actually should). When echoing the variable, it actually outputs:

5 A X

(these are three folders in my home directory) Then I noticed this happened when I was in my home directory, or in a directory like root (where I have the folders A, B and C). So, I changed cwd to to an empty, newly created directory and suddenly it worked. What exactly could be the cause of this? It only seems to happen with one letter folder names, but I thought this isn't supposed to happen since I escape the question mark with \?

  • Your problem is not the assignment to the variable, it's that you don't quote it in the echo. – RalfFriedl Jun 14 at 5:27
1

You should quote the variable in your echo command:

$ var=?
$ echo "$var"
?
-1

In all honesty. The correct escape method depends largely upon the shell used. The most common escape (as you already mentioned) is simply a backslash \. But, depending on it's usage, and the shell you use. The method may be different.

So. In conclusion. The correct answer can only be given if the shell you're using is provided. :)

  • Assuming a POSIX shell is not a too far-fetched thing to do. – Kusalananda Jun 14 at 19:17
  • Yes indeed. But the OP used Linux, and POSIX in the same sentence, and "Linux ain't POSIX". So which is it? ;) – somebody Jun 14 at 19:22
  • bash, which is the default shell on most Linuxes, is a POSIX shell in the sense that it implements the POSIX grammar and syntax, as does most other shells other than csh, tcsh, rc, and fish. Note that "Linux" does not handle ? in shell code in any particular way. It's the shell that does, so whether "Linux is POSIX" or not is besides the point. bash also happens to be the default shell on macOS, which is a certified Unix. – Kusalananda Jun 14 at 19:55
  • "It's the shell that does" -- that was my point. :) While I definitely agree they share the same grammar. I don't think the MacOS version is the same version, and I know the MacOS version is "certified" POSIX. But in the end, I think we're in agreement. :) – somebody Jun 14 at 20:01
  • And so, assuming that the user uses a POSIX shell is not too far fetched. – Kusalananda Jun 14 at 20:05

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.