Reputation: 798
I would be glad if somebody could explain me what this part of the code does
[ -n "${0%/*}" ] && cd ${0%/*}
. ./environment.sh
. ./readParams.sh
I understand that this script is reading from ./enviroment.sh
and ./readparams.sh
But i am really struggling to understand what the first line of the code does.So i can understand the whole process after this.
I would be glad if you could give me a site or anything that will help me understand such a syntax. I am a beginner in shell script so any help is appreciated.
Upvotes: 0
Views: 113
Reputation: 86954
That's a shell script, not python.
[ -n "${0%/*}" ] && cd ${0%/*}
That changes the current working directory to the directory where the shell script resides.
. ./environment.sh
. ./readParams.sh
That sources the two listed shell script, presumable stored within the same directory as the script being called.
To break down the first line, $0
will contain the first argument of the command i.e. the script being called. ${0%/*}
performs a parameter substitution to remove the trailing portion (from the last /
onwards) so this effectively gives you the directory name.
[ -n "${0%/*}" ]
translates to "if "${0%/*}"
results in a string that is not empty".
The whole line therefore translates to "if the executed script is prefixed with a path, then cd
to that directory".
p.s. I'm not convinced that's the best way to achieve that, but that's pretty much what it does. Personally, I would opt for the more readable cd $(dirname "$0")
, or for a more robust solution, see Getting the source directory of a Bash script from within.
Upvotes: 5
Reputation: 195229
first, this is not python at all, even not close!
[ -n "${0%/*}" ] && cd ${0%/*}
it used parameter expansion, you can man bash to see it.
basically, it cd
to the directory, which your script is located. for example:
if your script is at:
/foo/bar/baz/xxx.sh
the above line does cd /foo/bar/baz
the files:
environment.sh
readParams.sh
are in same directory of xxx.sh
Upvotes: 1