So I get that:
function global:prompt {
# Commands go here
}
Sets the prompt in powershell. I can use Get-Location
to get the current working directory. And I can cd ~
and be in my home dir.
But can I make the prompt use the tilde? E.g., if I'm in /home/mike
it should just show ~
.
I've tried testing with:
$pwd -contains $home
But the results aren't correct.
How can I use ~ in the prompt in powershell?
The tilde character ( ~ ) is shorthand notation for the current user's home folder.
Toggle between open windows of the same app Mac: cmd + ~ (tilde) Alternate between open windows of a single application.
The TAB key has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB , it changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).
`r`n is CRLF, the newline sequence composed of a CARRIAGE RETURN ( U+000D ) character immediately followed by an LF, used as a newline on Windows.
You can replace $HOME
with ~
using normal string replacement. Ex.
Get the current prompt-function:
Get-Content Function:\prompt
"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
# .Link
# http://go.microsoft.com/fwlink/?LinkID=225750
# .ExternalHelp System.Management.Automation.dll-help.xml
Then replace $home
with ~
when the current path is $home
or $home\*
.
Using switch (readable):
function global:prompt {
$path = switch -Wildcard ($executionContext.SessionState.Path.CurrentLocation.Path) {
"$HOME" { "~" }
"$HOME\*" { $executionContext.SessionState.Path.CurrentLocation.Path.Replace($HOME, "~") }
default { $executionContext.SessionState.Path.CurrentLocation.Path }
}
"PS $path$('>' * ($nestedPromptLevel + 1)) ";
}
Using regex (recommended):
function global:prompt {
$regex = [regex]::Escape($HOME) + "(\\.*)*$"
"PS $($executionContext.SessionState.Path.CurrentLocation.Path -replace $regex, '~$1')$('>' * ($nestedPromptLevel + 1)) ";
}
Using Split-Path
(ugly):
function global:prompt {
$path = $executionContext.SessionState.Path.CurrentLocation.Path
$p = $path
while ($p -ne "") {
if($p -eq $HOME) { $path = $path.Replace($HOME,"~"); break}
$p = Split-Path $p
}
"PS $path$('>' * ($nestedPromptLevel + 1)) ";
}
Demo:
PS C:\> cd ~
PS ~> cd .\Desktop
PS ~\Desktop>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With