Suppose I have in main.sh:
$NAME="a string"
if [ -f $HOME/install.sh ]
. $HOME/install.sh $NAME
fi
and in install.sh:
echo $1
This is supposed to echo "a string"
, but it echoes nothing. Why?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communitySuppose I have in main.sh:
$NAME="a string"
if [ -f $HOME/install.sh ]
. $HOME/install.sh $NAME
fi
and in install.sh:
echo $1
This is supposed to echo "a string"
, but it echoes nothing. Why?
Michael Mrozek covers most of the issues and his fixes will work since you are using Bash.
You may be interested in the fact that the ability to source a script with arguments is a bashism. In sh
or dash
your main.sh
will not echo anything because the arguments to the sourced script are ignored and $1
will refer to the argument to main.sh.
When you source the script in sh
, it is as if you just copy and pasted the text of the sourced script into the file from which it was sourced. Consider the following (note, I've made the correction Michael recommended):
$ bash ./test.sh
A String
$ sh ./test.sh
$ sh ./test.sh "HELLO WORLD"
HELLO WORLD
I see three errors:
Your assignment line is wrong:
$NAME="a string"
When you assign to a variable you don't include the $
; it should be:
NAME="a string"
You're missing then
; the conditional line should be:
if [ -f $HOME/install.sh ]; then
You're not quoting $NAME
, even though it has spaces. The source line should be:
. $HOME/install.sh "$NAME"
[ -f $HOME/install.sh ] && . $HOME/install.sh $NAME
; I should probably not do things like that when I'm looking for errors
Dec 20, 2010 at 19:01
simply set your parametrs before sourcing the script !
#!/bin/bash
NAME=${*:-"a string"}
if [[ -f install.sh ]];
then
set -- $NAME ;
. install.sh ;
fi
exit;
#!/bin/bash
echo " i am sourced by [ ${0##*/} ]";
echo " with [ $@ ] as parametr(s) ";
exit;
u@h$ ./main.sh some args
i am sourced by [ main.sh ]
with [ some args ] as parametr(s)
u@h$
--
just like they were command arguments: set -- -v foo -l bar -j "${bin}"
Sep 27, 2019 at 14:18