Can I create a Desktop Shortcut/Alias to a Folder from the Terminal?

Solution 1:

Try this on Terminal:

cd ~/Desktop
ln -s ~/Library/path/to/folder

Solution 2:

It's possible to do it in one line of Terminal. Let's say you want to alias to the file "/Users/me/Library/Preferences/org.herf.Flux.plist".

osascript -e 'tell application "Finder"' -e 'make new alias to file (posix file "/Users/me/Library/Preferences/org.herf.Flux.plist") at desktop' -e 'end tell'

You should replace to file with to folder if you have a folder.

Here's a shell script that allows you pass in a file or folder path to create the alias:

#!/bin/bash

if [[ -f "$1" ]]; then
  type="file"
else
  if [[ -d "$1" ]]; then 
    type="folder"
  else
    echo "Invalid path or unsupported type"
    exit 1
  fi
fi

osascript <<END_SCRIPT
tell application "Finder"
   make new alias to $type (posix file "$1") at desktop
end tell
END_SCRIPT

If you name this script make-alias.sh, chmod u+x make-alias.sh and put it in /usr/local/bin, you can run e.g. make-alias.sh ~/Library/Preferences.

Solution 3:

In case you need to target the link at a specific folder (or give it a specific name), you can use set name of result to "…" as in

#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "mkalias: specify 'from' and 'to' paths" >&2
    exit 1
fi

from="$(realpath $1)"
todir="$(dirname $(realpath $2))"
toname="$(basename $(realpath $2))"
if [[ -f "$from" ]]; then
    type="file"
elif [[ -d "$from" ]]; then
    type="folder"
else
    echo "mkalias: invalid path or unsupported type: '$from'" >&2
    exit 1
fi

osascript <<EOF
tell application "Finder"
   make new alias to $type (posix file "$from") at (posix file "$todir")
   set name of result to "$toname"
end tell
EOF

Solution 4:

#!/bin/bash

get_abs() {
  # $1 : relative filename
  echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
}


if [[ $# -ne 2 ]]; then
    echo "mkalias: specify 'from' and 'to' paths" >&2
    exit 1
fi

from=$(eval get_abs $1)  
todir=$(dirname $(eval get_abs $2))
toname=$(basename $(eval get_abs $2))
if [[ -f "$from" ]]; then
    type="file"
elif [[ -d "$from" ]]; then
    type="folder"
else
    echo "mkalias: invalid path or unsupported type: '$from'" >&2
    exit 1
fi

osascript <<EOF
tell application "Finder"
   make new alias to $type (posix file "$from") at (posix file "$todir")
   set name of result to "$toname"
end tell
EOF