Last active
August 29, 2015 14:14
-
-
Save fumiyas/b65f888b2bc1e352e659 to your computer and use it in GitHub Desktop.
ln-s-relative.sh - Make a symlink in relative path form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/dash | |
set -u | |
ln_s_relative() { | |
local root="" | |
if [ $# -eq 3 ]; then | |
local root="$1"; shift | |
fi | |
local target="$1"; shift | |
local linkname="$1"; shift | |
## Refuse relative paths in arguments | |
case "$target/$linkname" in | |
.|..|./*|../*|*/./*|*/../*|*/.|*/..) | |
echo "ln_s_relative: ERROR: Invalid argument" 1>&2 | |
return 1 | |
;; | |
esac | |
if [ -n "${root##/*}" ] || [ -z "$target" ] || [ -n "${target##/*}" ] || [ -z "$linkname" ] || [ -n "${linkname##/*}" ]; then | |
echo "ln_s_relative: ERROR: Invalid argument" 1>&2 | |
return 1 | |
fi | |
if [ -d "$root$linkname" ]; then | |
local dirname="$linkname" | |
else | |
local dirname=`/usr/bin/dirname "$linkname"` | |
fi | |
local root_from_linkname=`echo "$dirname" |/bin/sed 's#^/##;s#/$##;s#[^/][^/]*#..#g'` | |
local target_relative="$root_from_linkname$target" | |
[ "$dirname" = "/" ] && dirname="" | |
/bin/ln -s "$target_relative" "$root$dirname/${linkname##*/}" | |
} | |
if [ $# -lt 2 ] || [ $# -gt 3 ]; then | |
echo "Usage: $0 [ROOT] TARGET LINKNAME" | |
exit 1 | |
fi | |
ln_s_relative "$@" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment