ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

【realpath】一つ上のディレクトリに対して絶対パスを取得する方法

Makefile 内で docker を使っていたら以下のような問題に遭遇したため対応方法をここにメモします。
(一つ上のディレクトリをマウントさせたかったのですが...相対パスの指定はだめとのこと...)

docker: Error response from daemon: create ./../sample: "./../sample" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path.
See 'docker run --help'.

realpath

realpath コマンドは、相対パスを絶対パスに変換するコマンドです。

使い方

[.] や [..] やシンボリックリンクを展開し、相対パスを絶対パスに置換することが可能です。

NAME
       realpath - print the resolved path

SYNOPSIS
       realpath [OPTION]... FILE...

DESCRIPTION
       Print the resolved absolute file name; all but the last component must exist

       -e, --canonicalize-existing
              all components of the path must exist

       -m, --canonicalize-missing
              no path components need exist or be a directory

       -L, --logical
              resolve '..' components before symlinks

       -P, --physical
              resolve symlinks as encountered (default)

       -q, --quiet
              suppress most error messages

       --relative-to=DIR
              print the resolved path relative to DIR

       --relative-base=DIR
              print absolute paths unless paths below DIR

       -s, --strip, --no-symlinks
              don't expand symlinks

       -z, --zero
              end each output line with NUL, not newline

       --help display this help and exit

       --version
              output version information and exit

AUTHOR
       Written by Padraig Brady.

REPORTING BUGS

Makefile

一つ上のディレクトリに対して絶対パスを取得するサンプルコードは以下の通りです。

成功

SAMPLE_DIR=$(shell realpath ..)/sample

.PHONY : test
test:
	@echo ${SAMPLE_DIR}

失敗

'${PWD%/*}'のような文字列置換は、Makefile だとうまくいきませんでした。

SAMPLE_DIR=${PWD%/*}/sample

.PHONY : test
test:
	@echo ${SAMPLE_DIR}