How to remove a path from system path(`$PATH`) using terminal commands?

In your current shell (your current session of gnome-terminal) you can do this using:

export PATH=${PATH%:/home/avinash/Desktop/raj}

In general:

${string%substring}

deletes shortest match of $substring from back of $string.

Check out String manipulation for more info.


Running export PATH=$PATH:/... doesn't set your PATH system-wide. It's just a shell variable. Start a new shell and BOOM, it's gone. Obviously if you've added that to ~/.bashrc (or another environment bootstrap file) you'll have to revert that change but it doesn't sound like your problem here.

If you're desperate not to start a new shell, you could set it by removing it manually, with:

export PATH=/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

If you want use it as a command, here is a little script:

#!/bin/bash

# This script removes folder from PATH variable
# Folders to remove reading as arguments

if [ $# -lt 1 ]; then
    echo "You should give at least one argument"
    echo "For example"
    echo "$0 /usr/local/bin"
else
    FOLDERS_TO_REMOVE=`echo $@ | sed 's/ /|/g'`

    echo "You actually PATH variable is:"
    echo $PATH
    echo "###"

    PATH=$( echo ${PATH} | tr -s ":" "\n" | grep -vwE "(${FOLDERS_TO_REMOVE})" | tr -s "\n" ":" | sed "s/:$//" )

    echo "Now you need to run"
    echo "export PATH=$PATH"
fi

Name it unexport, and add it to your PATH.

Usage:

unexport /usr/local/bin /bin /sbin

This script does not change your actually PATH. If you want script to do it, you should change last line. Substitute echo "export PATH=$PATH" to export PATH=$PATH

Tags:

Command Line