Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  6] [ 0]  / answers: 1 / hits: 381  / 3 Years ago, fri, june 25, 2021, 11:59:01

I recently installed a few softwares and needed to add their bin/ directories to my PATH. Nothing abnormal so far. But I decided to be smart about it, and rewrote a part of my .profile so I didn't have to copy/paste the same few lines of codes over and over. Here was my idea:



# Create an array with directories to be added to PATH
declare -a addpath=("$HOME/bin" "$HOME/.cabal/bin" "/opt/vert.x/current/bin")

# Add directories recursively
for dir in "${addpath[@]}"; do
if [ -d "$dir" ]; then
PATH="$dir:$PATH"
fi
done


I thought this had worked well.. until I rebooted my PC and got locked out of my session when trying to log in. It took me a while to figure out that it was actually because of my .profile; once I commented those lines out, I was able to log into my session without being bounced back.



My question is; what did I do wrong with these lines? Is there a syntax error? Is there an other/better way to do that? What happened?


More From » bash

 Answers
2

In the default setup on Ubuntu 12.04, the .profile file is loaded by /usr/sbin/lightdm-session. This is shell script, executed by /bin/sh.



On Ubuntu, /bin/sh is dash. You've used features of bash that dash doesn't support. Dash and Bash both have the same core features, but dash sticks to these core features in order to be fast and small whereas bash adds a lot of features at the cost of requiring more resources. It is common to use dash for scripts that don't need the extra features and bash for interactive use (though zsh has a lot of nicer features).



Dash doesn't have arrays, nor the declare built-in, so it's bombing out on that line. You can put the list of paths inline:



for dir in "$HOME/bin" "$HOME/.cabal/bin" "/opt/vert.x/current/bin"; do
if [ -d "$dir" ]; then
PATH="$dir:$PATH"
fi
done


See keep duplicates out of $PATH on source if you want to make sure not to end up with duplicate entries.






Rather than add new directories to PATH for each program you install, you might want to set up symbolic links in an existing directory instead. For ~/.cabal/bin, you'll want to have it in your path because executables there will be coming and going; I'd put it at the end of the PATH though, to avoid potential conflicts with existing programs on your system. ~/bin is already in your PATH on Ubuntu. For programs that you install manually such as vert.x, stow or xstow is nice for managing symbolic links. See Keeping track of programs for an introduction to stow.


[#29874] Saturday, June 26, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hirtieve

Total Points: 207
Total Questions: 104
Total Answers: 114

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
;