Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle relative paths in a bash setup script?

Tags:

bash

shell

I often run into the situation where I would like to provide some kind of 'setup' or 'install' script, for something like a git repository, although it could also be used in other situations.

Just to be clear: with 'setup script' I mean a script which places some files, checks some things, creates certain dependencies and so on.

The problem is that if I want to use resources relative to the script or want to create links that target files in the repository I somehow need to be able to reference resources relative to the repository root or build absolute paths.

Currently I always go with this:

SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd)
ROOT=$(realpath "$SCRIPT_DIR/..")

But this seems really bad, as it hard to understand and basically replicated in every repo or even file.

Is there a better way to do this? Are scripts like this unwanted?

like image 978
AK_is_curious Avatar asked Oct 15 '25 14:10

AK_is_curious


1 Answers

Is there a better way to do this?

No.

Are scripts like this unwanted?

No. That's normal.

Is there another way to go about this?

My fingers are used to typing "$(dirname "$(readlink -f "$0")")", but that's not better.

Also do not use UPPER CASE VARIABLES. Not only they shout, but are meant for environment variables, like PWD LINES COLUMNS DISPLAY UID IFS USER etc. Prefer lower case variables in your scripts. (I would say that ROOT is a very common and thus bad variable name.)

like image 130
KamilCuk Avatar answered Oct 17 '25 04:10

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!