Shell Prompt That Is Based on Location in Filesystem

Shell prompt that is based on location in filesystem

You can hook into cd to change the prompt every time you are changing the working directory. I've asked myself often how to hook into cd but I think that I now found a solution. What about adding this to your ~/.bashrc?:

#
# Wrapper function that is called if cd is invoked
# by the current shell
#
function cd {
# call builtin cd. change to the new directory
builtin cd $@
# call a hook function that can use the new working directory
# to decide what to do
color_prompt
}

#
# Changes the color of the prompt depending
# on the current working directory
#
function color_prompt {
pwd=$(pwd)
if [[ "$pwd/" =~ ^/home/ ]] ; then
PS1='\[\033[01;32m\]\u@\h:\w\[\033[00m\]\$ '
elif [[ "$pwd/" =~ ^/etc/ ]] ; then
PS1='\[\033[01;34m\]\u@\h:\w\[\033[00m\]\$ '
elif [[ "$pwd/" =~ ^/tmp/ ]] ; then
PS1='\[\033[01;33m\]\u@\h:\w\[\033[00m\]\$ '
else
PS1='\u@\h:\w\\$ '
fi
export PS1
}

# checking directory and setting prompt on shell startup
color_prompt

How do I get the directory where a Bash script is located from within the script itself?

#!/usr/bin/env bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.

It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:

#!/usr/bin/env bash

SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
SOURCE=$(readlink "$SOURCE")
[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )

This last one will work with any combination of aliases, source, bash -c, symlinks, etc.

Beware: if you cd to a different directory before running this snippet, the result may be incorrect!

Also, watch out for $CDPATH gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2 on Mac). Adding >/dev/null 2>&1 at the end of your cd command will take care of both possibilities.

To understand how it works, try running this more verbose form:

#!/usr/bin/env bash

SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET=$(readlink "$SOURCE")
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE=$TARGET
else
DIR=$( dirname "$SOURCE" )
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR=$( dirname "$SOURCE" )
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"

And it will print something like:

SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'

Start WSL Ubuntu in specific or current folder on Windows

I'm on Windows 10 Home with May Update and have Ubuntu 18.04 for WSL installed, I can open the console in any folder with Shift + Right Click and selecting the Open Linux shell here option

Sample Image

Equivalent of where command prompt command in C#

I don't think there is a built-in method in the Common Language Runtime to do this for you, but you can certainly do it yourself:

  • Get the value of the PATH environment variable
  • Split it on ; delimiters to get a list of directories in the path
  • Check each of those directories to see if it contains program

Example:

public static string FindInPath(string filename)
{
var path = Environment.GetEnvironmentVariable("PATH");
var directories = path.Split(';');

foreach (var dir in directories)
{
var fullpath = Path.Combine(dir, filename);
if (File.Exists(fullpath)) return fullpath;
}

// filename does not exist in path
return null;
}

Don't forget to add .exe to the filename. (Or, you could modify the code above to search for any executable extension: .bat, .com, .exe; or perhaps even any extension at all.)

Encountering Fatal Python error when I try to use pip in command prompt

The answer was to uninstall and reinstall python, this time telling it to set environment variables. That did the trick.

How can use CD command in command prompt to change to a folder named only with a space?

I was able to create the directory with a fully-qualified path by mkdir "\\?\D:\ ". However that folder can't be accessed by either Explorer or cmd

In Windows Explorer entering the folder always show the parent folder's content although it has actually entered the subfolder, therefore you can't do anything with that content, and Explorer's title bar becomes blank since it displays the folder name. In cmd cd stays on the parent folder unless you use the trick in SomethingDark's answer. You probably need to remove or rename it

Sad to say I've yet to find a way to rename the folder. However it's easy to delete it with the same path

rmdir "\\?\D:\ "

A normal path will also work but you always need a slash at the end

mkdir ".\ \"
rmdir ".\ \"

It's possible to store files in that folder

D:\>>".\ \a.txt" echo abc

D:\>type ".\ \a.txt"
abc

Once you have some content in the folder Explorer can now enter it normally. Unfortunately cmd still can't change into it. A fully-qualified path may help, unluckily cmd doesn't support it. However PowerShell does support it and can enter it like Explorer


PS D:\> cat '.\ \a.txt'
abc
PS D:\> cd '.\ \'
cd : An object at the specified path D:\ does not exist.
At line:1 char:1
+ cd '.\ \'
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.SetLocationCommand

PS D:\> cd '\\?\D:\ \'
PS Microsoft.PowerShell.Core\FileSystem::\\?\D:\ > dir
Directory: \\?\D:\

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 8/23/2018 3:39 PM 5 a.txt

Sadly once you entered you can't use cd .. to go back and you must use fully-qualified path again


PS Microsoft.PowerShell.Core\FileSystem::\\?\D:\ > cd ..
cd : Cannot find path '\\?\D:' because it does not exist.
At line:1 char:1
+ cd ..
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (\\?\D::String) [Set-Location], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

PS Microsoft.PowerShell.Core\FileSystem::\\?\D:\ > echo `"$(pwd)`"
"Microsoft.PowerShell.Core\FileSystem::\\?\D:\ "

Windows PowerShell: changing the command prompt

Just put the function prompt in your PowerShell profile (notepad $PROFILE), e.g.:

function prompt {"PS: $(get-date)>"}

or colored:

function prompt
{
Write-Host ("PS " + $(get-date) +">") -nonewline -foregroundcolor White
return " "
}

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

Use realpath

$ realpath example.txt
/home/username/example.txt


Related Topics



Leave a reply



Submit