0

I would like to install something from github in a bash script but I try to verify if the folder exists or not:

BLUE "Installing LS_COLORS..."

if [ ! -d "~/opt/LS_COLORS" ]

then
        git clone https://github.com/trapd00r/LS_COLORS.git ~/opt/LS_COLORS && cd ~/opt/LS_COLORS
        cat lscolors.sh >> ~/.bashrc
        source ~/.bashrc
else

        GREEN "LS_COLORS already installed"

fi

The problem is that the LS_COLORS dir does not empty and this is not working properly. I can not get into the else part.

Artur Meinild
  • 21,605
  • 21
  • 56
  • 89
torabi12
  • 1
  • 1
  • Does not empty or is not empty? – David Oct 26 '22 at 13:16
  • 1
    Never EVER use relative paths in scripts (never use `~`). Please rewrite your script with absolute paths, and revise your post with the complete script with absolute paths. – Artur Meinild Oct 26 '22 at 13:19
  • @ArturMeinild please add *why* a behavior is wrong - instead of just saying it is wrong - to make your comment more constructive. – Natan Oct 26 '22 at 13:41
  • Further explanation: The best strategy is to define every directory you need as a variable in the beginning of the script, and then refer to the variables as you go along. Then you'll be sure that every file and directory is referenced correctly. – Artur Meinild Oct 26 '22 at 13:41
  • With relative paths, you rely on correctly using `cd` throughout the entire script, which is not as reliable. – Artur Meinild Oct 26 '22 at 13:43
  • 2
    The problem isn't the use of `~` per se - it's the fact that it's quoted. See for example [Why isn't tilde recognised as home folder in this case?](https://askubuntu.com/questions/1192981/why-isnt-tilde-recognised-as-home-folder-in-this-case) – steeldriver Oct 26 '22 at 13:45
  • Then there are 2 related issues - 1) that it doesn't expand, and 2) that use of relative paths is unreliable in general. Using absolute paths solves both issues. – Artur Meinild Oct 26 '22 at 13:55
  • 1
    @ArturMeinild *when expanded by the shell*, `~` is as absolute as `$HOME` is - see for example [Is `~/Documents` a relative or an absolute path?](https://unix.stackexchange.com/questions/221970/is-documents-a-relative-or-an-absolute-path) – steeldriver Oct 26 '22 at 14:14
  • You're right, if this is a "per user" script, then `$HOME` would be the best option. – Artur Meinild Oct 26 '22 at 15:13

1 Answers1

0

It looks like the path was not correct, I added the full path all the places:

BLUE "Installing LS_COLORS..."
if [ ! -d "/home/torabi12/opt/LS_COLORS/" ]
then
      git clone https://github.com/trapd00r/LS_COLORS.git /home/torabi12/opt/LS_COLORS
      cat /home/torabi12/opt/LS_COLORS/lscolors.sh >> ~/.bashrc
      source ~/.bashrc
else
      GREEN "LS_COLORS already installed"
fi

and now it is working. Thank you for all the replies.

torabi12
  • 1
  • 1