sorin
sorin

Reputation: 170856

How to I get the first directory from the PATH environment variable in bash?

Assuming that your PATH environment variable contains a list of paths, separated by :, how do I get only the first folder from this list into another variable?

Upvotes: 3

Views: 5811

Answers (5)

user8017719
user8017719

Reputation:

Either expansion:

mydir=${PATH%%:*}

Or read (bash 2.04+):

IFS=':' read -d '' mydir t <<<"$PATH"

Or better (bash 2.04+ also but not using a null delimiter):

IFS='' read -d ':' mydir <<<"$PATH"

are good solutions.

Upvotes: 3

Hannu
Hannu

Reputation: 12215

How about using awk?

foo=`echo $PATH | awk -F':' '{ print $1}'`

Upvotes: 3

Jeremy Gurr
Jeremy Gurr

Reputation: 1623

I assume you want to do it with a bash command. Try this:

echo ${PATH%%:*}

Upvotes: 10

anubhava
anubhava

Reputation: 786339

One way to read first entry be using read with correct IFS:

IFS=: read firstPath _ <<< "$PATH"

echo "$firstPath"

You can also use IFS to populate an array and get any Nth position from array using index:

IFS=: read -ra arr <<< "$PATH"

echo "First entry: ${arr[0]}"
echo "Second entry: ${arr[1]}"
echo "Fifth entry: ${arr[4]}"

Another bash solution is stripping everything after first ::

firstPath="${PATH%%:*}"

Upvotes: 3

sorin
sorin

Reputation: 170856

So far I was able to get this using MYDIR=$(sed 's/:/\n/' <<< "$PATH" | head -n 1) but I would be happy to see a much nicer implementation.

Upvotes: 1

Related Questions