Reputation: 170856
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
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
Reputation: 1623
I assume you want to do it with a bash command. Try this:
echo ${PATH%%:*}
Upvotes: 10
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
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