How to manage the file path in big project

  |   Source

It's not good practice to use relative path in big project.

Reasons:

  • If file B refer to file A with "../A". Then B's position in the project *CANNOT be changed. Or else its reference to A will be wrong.
  • Relative path is not intuitive when debugging.
  • If the dependency is complex. Figure out the right path is mission impossible. For example, file A refer to file B with "./a/../../B" and file B refer to file C "../../b/C".

So you should ALWAYS use the absolute path.

Absolute path is tedious to type and not portable.

It could be improved a little bit be use an environment variable to replace the common prefix of the full path.

For example, we can replace absolute path "/home/cb/projects/app1/src/test.c" with "$TTAGROOT/src/test.c", if the value of environment variable TTAGROOT is "/home/cb/projects/app1".

Insert below code into ~/.bashrc so TTAGROOT value is set when you logged into bash:

export TTAGROOT="/home/cb/projects/app1"

In you script to do the real job, you could make TTAGROOT optional and still use your full path happily. It's just one bash liner.

Here is a sample file named test.sh:

#!/bin/bash
[ -z "$TTAGROOT" ] && TTAGROOT="hard-coded-full-path"
echo "TTAGROOT = $TTAGROOT"

You could use test.sh without $TTAGROOT. Or you can set up default value of $TTAGROOT in ~/.bashrc as I already mentioned.

Or you can override the TTAGROOT value when you executing "test.sh":

TTAGROOT="hello" ./test.sh

BTW, don't abuse this technique. Set one environment variable for the root directory of project is enough.

Comments powered by Disqus