help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: how to (safely) escape an arbitrary string for use in PS1


From: Koichi Murase
Subject: Re: how to (safely) escape an arbitrary string for use in PS1
Date: Thu, 20 May 2021 09:40:48 +0900

2021年5月20日(木) 3:03 Christoph Anton Mitterer <calestyo@scientia.net>:
> Now is there any safe way for escaping that?
> I guess bash's builtin printf '%q' cannot be used here, because it
> escapes more than what PS1 would expand/substitute.

It seems that you want the way to escape a string such that the string
would be printed literally for both sides of the option `promptvars'.
I suspect it is impossible. In processing the prompt strings, there
are two phases:

The first one is the escape sequences for the prompts, such as \u for
usernames, etc. To escape the string from the first phase, you can
just replace all the backslashes with double backslashes.

The second one is the evaluation of ${...}, $((...)), $(...), `...`,
\", \\, \$, \`, etc. The problem is that `shopt -u promptvars'
 completely turns off the second phase. If you think about the case
`shopt -u promptvars', you need to pass the literal string to this
phase. But, if you also think about the case `shopt -s promptvars',
that string should not be modified by the second phase. It is not
possible for arbitrary strings. One can set the prompt strings for
each case of promptvars separately, or one can remove all \, $, and `
in the string. To summarize:

For `shopt -s promptvars`:

s=${s//'\'/'\\\\'}
s=${s//'$'/'\\$'}
s=${s//'`'/'\\`'}

For `shopt -u promptvars':

s=${s//'\'//'\\'}

Or one might give up all the special characters:

s=${s//['\$`']}

--
Koichi



reply via email to

[Prev in Thread] Current Thread [Next in Thread]