Last Updated: February 25, 2016
·
1.414K
· frank-dspeed

SHELL SCRIPT: Add your Current Directory to PATH Envirment

HOWTO Work with PATH Envirment var in Linux Shell

Little Script to extend PATH var with current dir or a given argument
befor or after the current PATH var

The Script is well documented used nice Shell syntax for comments
Its called Substitution it brings a var in a other Scope ;)
as you see it works nice i hope it will help you to document your scripts better

greetings

#!/bin/bash

########### 
# Author: Frank Lemanschik
# Scriptname: pathadd 
# Version: v1.2
# Last Modifyed: 14.04.2014#04:23 UCT
# URL: 
# Usage: addpath [path] 
# Notes: Replace [path] with /home/bla/project
#              if none supplyed current workdir gets used
# returns: 0 if no error and 1 if error 
###########



pathadd() {
## This Looks for the given /home/user like argument 
## else auto use current directory
if [[ -z "$1" `# Check if argument is given like "/home/user/project"`]]; then 
    if [ "$1" = "after" `# try if argument is "after"`]; then
        "2"="after" `# move after to $2`
    fi
    "1"=$PWD `# use current directory as argument`
fi     

## Makes Save argument is a Directory and then adds it to begin of PATH 
## if after is supplyed it gets added to the end of PATH
## and final shows summary or errors
if [ -d "$1" `# Check if directory exists and if it is a directory`]; then 
    if [[ ":$PATH:" != *":$1:"* `# check not already set in PATH ?`]]; then
        if [ "$2" = "after" `# check if add after`] ; then
            PATH=$PATH:$1
            echo "Added: $1 after PATH"
            return 0
        else
            PATH=$1:$PATH
            echo "Added: $1 before PATH"
            return 0
        fi

    else
        echo "INFO: $1 Is Already in PATH"
        return 0
    fi
else
    echo "Error: $1 Is not a Valid Directory"
    return 1
fi
}

shorter version

if you like it small and none verbose and error handling sounds like greek for you?

 pathadd() {
    if [ -d "$1" ] &&[[ ":$PATH:" != *":$1:"* ]]; then
        if [ "$2" != "after" ] ; then
            PATH=$1:$PATH
        else
            PATH=$PATH:$1
        fi 
    fi
}