Should you change the current directory in a shell script?
-
11-06-2021 - |
Question
I've always mentally regarded the current directory as something for users, not scripts, since it is dependent on the user's location and can be different each time the script is executed.
So when I came across the Java jar utility's -C
option I was a little puzzled.
For those who don't know the -C
option is used before specifying a file/folder to include in a jar. Since the path to the file/folder is replicated in the jar, the -C
option changes directories before including the file:
in other words:
jar -C flower lily.class
will make a jar containing the lily.class
file, whereas:
jar flower/lily.class
will make a flower
folder in the jar which contains lily.class
For a jar-ing script I'm making I want to use Bourne wild-cards folder/*
but that would make using -C
impossible since it only applies to the next immediate argument.
So the only way to use wild-cards is run from the current directory; but I still feel uneasy towards changing and using the current directory in a script.
Is there any downside to using the current directory in scripts? Is it frowned upon for some reason perhaps?
Solution
I don't think there's anything inherently wrong with changing the current directory from a shell script. Certainly it won't cause anything bad to happen, if taken by itself.
In fact, I have a standard script that I use for starting up a Java-based server, and the very first line is:
cd `dirname $0`
This ensures that the rest of the commands in the script are executed in the directory that contains the script file itself (useful when a single machine is hosting multiple server instances), regardless of where the shell script was actually invoked from. Without changing the current directory in the script, it would only work correctly if the user remember to manually cd
into the corresponding directory before running the script.
In this case, performing the cd
operation from within the script removes a manual step from the server startup/shutdown process, and makes things slightly less error-prone as a result.
So as with most things, there are legitimate uses for this sort of thing. And I'm sure there are also some questionable ones, as well. It really depends upon what's most appropriate for your specific use-case. Which is something I can't really comment on...I always just let maven
build my JAR's for me.