Reputation: 8505
I have a simple script called abc.sh as follows, that sets the environment variables
#!/bin/bash
sourcePath () {
filename=`basename $0`
current_dir="./"$filename
if [ "$current_dir" = "$0" ]; then SRC_DIR=$(pwd)
SRC_DIR=$(cd "$SRC_DIR/.."; pwd)
else SRC_DIR=$(cd "$(dirname "$0")/.."; pwd)
fi
}
sourcePath
echo $SRC_DIR
export SRC_DIR
I would like this script to set the variable SRC_DIR in my current shell environment. Hence, when i do source abc.sh, i get an error saying invalid options to dirname. But if i run this file with ./abc.sh, i dont get any error, but then it wont export the variable
Upvotes: 1
Views: 2423
Reputation: 5036
Part of the problem is that $0 has a different value when you source the script, because sourcing is just the same as typing commands directly to the shell. So when you run the script, $0 is abc.sh, but when you source it, $0 is /bin/bash. You can see this by setting the -x flag:
set -x
source abc.sh
But I can't be sure that this is the only problem, because when I source the script I don't get an error from dirname, and the script prints "/".
Upvotes: 3
Reputation: 96258
If you do source
, then $0
won't change (won't be the name of your executable, e.g.: ./abc.sh
).
Upvotes: 0