Passing variables to a bash manuscript when sourcing it

Suppose I have in main.sh:

$NAME="a string"
if [ -f $HOME/install.sh ]
    . $HOME/install.sh $NAME
fi

and also in install.sh:

echo $1

This is intended to resemble "a string", yet it mirrors absolutely nothing. Why?

0
2019-05-13 05:39:52
Source Share
Answers: 2

I see 3 mistakes:

  1. Your assignment line is incorrect:

    $NAME="a string"
    

    When you assign to a variable you do not include the $ ; it need to be:

    NAME="a string"
    
  2. You are missing out on then ; the conditional line need to be:

    if [ -f $HOME/install.sh ]; then
    
  3. You are not pricing estimate $NAME, despite the fact that it has rooms. The source line need to be:

    . $HOME/install.sh "$NAME"
    
0
2019-05-17 20:00:02
Source

Michael Mrozek covers a lot of the concerns and also his solutions will certainly function given that you are making use of Bash.

You might want the reality that the capacity to source a manuscript with debates is a bashism. In sh or dash your main.sh will certainly not resemble anything due to the fact that the debates to the sourced manuscript are overlooked and also $1 will certainly describe the argument to main.sh.

When you source the manuscript in sh, it is as if you simply replicate and also pasted the message of the sourced manuscript right into the documents where it was sourced. Take into consideration the following (note, I've made the improvement Michael advised):

$ bash ./test.sh
A String
$ sh ./test.sh

$ sh ./test.sh "HELLO WORLD"
HELLO WORLD
0
2019-05-17 19:58:39
Source