Skip to content

hugojosefson/realpath-compat

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

realpath-compat

An implementation of realpath(1) that should work everywhere.

Installation

Copy this function into your shell script:

realpath_compat(){ if [ $# -eq 0 ];then echo "Usage: realpath_compat FILE [FILE ...]">&2;return 1;fi;while [ $# -gt 0 ];do file="$1";shift;if ! [ -e "$file" ];then echo "realpath_compat: $file: No such file or directory">&2;return 1;fi;realpath "$file" 2>/dev/null||readlink -f "$file" 2>/dev/null||zsh -c 'echo ${0:A}' "$file" 2>/dev/null||python3 -c "import os; import sys; print(os.path.realpath(sys.argv[1]))" "$file" 2>/dev/null||node -e "console.log(require('fs').realpathSync(process.argv[1]))" "$file" 2>/dev/null||echo "realpath_compat: $file: Could not resolve real path">&2;done;}

Alternatively, copy the non-minified version found in realpath-compat.

Usage

Call the function, with some file(s) as argument(s).

Example:

#!/bin/sh
set -e

realpath_compat(){ if [ $# -eq 0 ];then echo "Usage: realpath_compat FILE [FILE ...]">&2;return 1;fi;while [ $# -gt 0 ];do file="$1";shift;if ! [ -e "$file" ];then echo "realpath_compat: $file: No such file or directory">&2;return 1;fi;realpath "$file" 2>/dev/null||readlink -f "$file" 2>/dev/null||zsh -c 'echo ${0:A}' "$file" 2>/dev/null||python3 -c "import os; import sys; print(os.path.realpath(sys.argv[1]))" "$file" 2>/dev/null||node -e "console.log(require('fs').realpathSync(process.argv[1]))" "$file" 2>/dev/null||echo "realpath_compat: $file: Could not resolve real path">&2;done;}

my_real_path="$(realpath_compat "$0")"
echo "This script's real path is: ${my_real_path}, and that's true even if you call it via a symlink."

License

realpath-compat by Hugo Josefson is marked with CC0 1.0