user6226295
user6226295

Reputation:

How can I use source with variables?

I have tried multiple ways to get this to work, but no go: I just want to use $path in my source command.

#!/bin/bash

path="~/root/config/bash/"

source ~/root/config/bash/_private.sh
source ~/root/config/bash/config.sh

Upvotes: 0

Views: 258

Answers (3)

heemayl
heemayl

Reputation: 42137

Tilde (~) will be treated literally in a path when put inside quotes, in a variable declaration, so source $path won't work.

You can:

  • Use eval (be careful):

    source "$(eval echo $path)"
    
  • Or use alphabetic full path:

    path=/home/user/root/config/bash/
    
  • Or if the user is same as the login user, use $HOME:

    path="$HOME"/root/config/bash/
    
  • Or keep ~ outside of quotes

Upvotes: 3

Cyrus
Cyrus

Reputation: 88989

path=~/"root/config/bash/"
source "$path"

Upvotes: 2

Kevin M Granger
Kevin M Granger

Reputation: 2545

Bash parameters are expanded by the shell, before the command sees them as arguments.

source "$path" is all you need.

Unless you're talking about using it as a prefix, in which case, you could do:

source "${path}/_private.sh", etc.

However, if you're talking about using $path as if it were $PATH, and let it look for files there if they can't be found elsewhere, that would require custom logic.

Upvotes: 1

Related Questions