24 votos

¿Puedo crear un acceso directo/alias a una carpeta desde el terminal?

Me gustaría crear un acceso directo en el escritorio a una carpeta específica, enterrada en lo más profundo de ~/Library/ . Library está oculto por defecto en Lion, y me gustaría mantenerlo así, por una serie de razones. ¿Existe una acción de línea de comandos de un solo paso que pueda utilizar para crear un acceso directo en el escritorio a una ruta determinada? Me gustaría evitar soluciones que impliquen desocultar la Biblioteca, crear el Alias usando el Finder, y volver a ocultarlo. Sé cómo hacer eso, pero para mis propósitos, sería preferible una sola línea que se pueda pegar en la Terminal y terminar con ella.

17voto

erichui Puntos 1488

Es posible hacerlo en una línea de Terminal. Digamos que quieres poner un alias al archivo "/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'

Debe reemplazar to file con to folder si tiene una carpeta.

Aquí hay un shell script que permite pasar una ruta de archivo o carpeta para crear el 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

Si nombras este script make-alias.sh , chmod u+x make-alias.sh y ponerlo en /usr/local/bin puede ejecutar, por ejemplo make-alias.sh ~/Library/Preferences .

0 votos

Will ~/Library/Preferences/org.herf.Flux.plist" o es necesario incluir explícitamente el nombre de usuario en el comando del Terminal?

0 votos

Acabo de intentar usar ~ y no funciona con la línea osascript comando. Sugiero usar el archivo script en su lugar, porque el ~ se convierte automáticamente.

0 votos

Hmm. Parece que se rompe en los nombres de archivo con espacios como /Library/Application Support/

13voto

Stephan Puntos 131

Prueba esto en la Terminal:

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

5 votos

Creo que querías decir ln -s ~/Library/path/to/folder folder . Una pequeña desventaja de este método (es decir, el enlace simbólico) es que el enlace se romperá si el "original" (es decir, el objetivo) se mueve o cambia de nombre.

2 votos

El segundo argumento folder no es necesario. Si lo omite, ln crea un enlace con el mismo nombre que la carpeta original.

0 votos

Ah, tienes razón. Me dio un error antes, pero debo haber escrito mal algo.

2voto

Andrew McClure Puntos 11
#!/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

0 votos

Una explicación de cómo funciona el script sería útil

0 votos

Igual que script anterior pero sin necesidad de realpath

1voto

Jamie Puntos 332

En caso de que necesite dirigir el enlace a una carpeta específica (o darle un nombre específico), puede utilizar set name of result to "…" como en

#!/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

0voto

Ehtesh Choudhury Puntos 1395

Para la gente que quiera una solución en Python, aquí hay una función que envuelve a applescript y luego llama a subprocess.call:

def applescript_finder_alias(theFrom, theTo):
    """
    (theFrom, theTo)
    create a short/alias
    theFrom, theTo: relative or abs path, both folder or both file
    """
    # https://apple.stackexchange.com/questions/51709
    applescript = '''
    tell application "Finder"
       make new alias to %(theType)s (posix file "%(theFrom)s") at (posix file "%(todir)s")
       set name of result to "%(toname)s"
    end tell
    '''
    def myesp(cmdString):
        import os, inspect, tempfile, subprocess
        caller = inspect.currentframe().f_back
        cmd =  cmdString % caller.f_locals

        fd, path = tempfile.mkstemp(suffix='.applescript')
        try:
            with os.fdopen(fd, 'w') as tmp:
                tmp.write(cmd.replace('"','\"').replace("'","\'")+'\n\n')
            subprocess.call('osascript ' + path, shell=True, executable="/bin/bash")
        finally:
            os.remove(path)
        return None
    import os
    theFrom = os.path.abspath(theFrom)
    theTo = os.path.abspath(theTo)
    if os.path.isfile(theFrom): 
        theType = 'file'
    else:
        theType = 'folder'
    todir = os.path.dirname(theTo)
    toname = os.path.basename(theTo)
    myesp(applescript)

AppleAyuda.com

AppleAyuda es una comunidad de usuarios de los productos de Apple en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X