Contents

Handling Absolute Paths Correctly in Makefile and Shell

Handling absolute paths in Makefile and shell (mainly Bash).

Copyright notice: This is an original article by xwi88, licensed under CC BY-NC 4.0. Commercial use is prohibited; please cite the source when reposting. Follow at https://github.com/xwi88

Makefile

make version: 3.81

BASEDIR = $(dir $(realpath $(firstword $(MAKEFILE_LIST))))

1
2
3
4
5
6
7
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i386-apple-darwin11.3.0

Linux Shell

Bash version: 5.1

  • DIR=$(cd $(dirname $0) && pwd)
  • DIR=$(cd $(dirname $0); pwd)
  • DIR=$(cd dirname $0; pwd)
  • DIR=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
  • ROOT_DIR="${DIR##*/}"
  • FILE_NAME=$(basename "$0")
Warning

BASH_SOURCE only works where a bash shell is available

cat /etc/shells lists the shells supported on this machine

Example

For working examples of the above, see: docker-compose-resources