tutorial_de_fish

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anterior Revisión previa
Próxima revisión
Revisión previa
tutorial_de_fish [2022/06/28 21:20] – [Exportar (Variables de Intérprete)] perontutorial_de_fish [2023/06/06 19:42] (actual) – [Funciones incorporadas] peron
Línea 5: Línea 5:
  
 ==== Activar el intérprete de comandos Fish ==== ==== Activar el intérprete de comandos Fish ====
-<code bash>chpass</code> +En nuestro sistema [[BSD]] podrás [[interpretes de comandos#cambiar el interprete|cambiar el intérprete de comandos]] con chsh. 
- +<code bash>chsh -s /usr/local/bin/fish</code> 
-En la línea ''Shell'', asegúrate de agregar esta ruta: +Deberás reiniciar la sesión para que surta efecto.
- +
-<code bash>/usr/local/bin/fish</code> +
- +
-Guarda los cambios y reinicia la sesión.+
 ==== Ejecutar Comandos ==== ==== Ejecutar Comandos ====
  
  
-[[Fish shell]] ejecuta comandos como cualquier otra [[interpretes de comandos|shell]]: para hacerlo ingresa un comando, seguido por sus argumentos. Los espacios son separadores+[[fish|Fish shell]] ejecuta comandos como cualquier otra [[interpretes de comandos|shell]]: para hacerlo ingresa un comando, seguido por sus argumentos. Los espacios son separadores
  
 <code bash> <code bash>
Línea 226: Línea 222:
  
 env | grep MiVariable env | grep MiVariable
-MyVariable=AlgunValue</code>+MiVariable=AlgunValor</code>
  
-También puedes des-exportarlas con **--unexport** or **-u**.+También puedes des-exportarlas con **--unexport** **-u**.
  
 ¡Esto también opera a la inveersa! Si fish comienza con algo más, heredará las variables exportadas por su proceso progenitor. De modo que si tu emulador de terminar ejecuta fish, y exporta ¡Esto también opera a la inveersa! Si fish comienza con algo más, heredará las variables exportadas por su proceso progenitor. De modo que si tu emulador de terminar ejecuta fish, y exporta
-''$LANG'' con el valor ''es_AR.UTF-8'', fish recibirá tal configuración. Y cualquier emulador que inicies al cual le otorgues variables también las pasarán, a no ser que específicamente decidas no hacerlo. Esta es la manera en la cual fish recibe usualmente los valores de ''$LANG'', ''$PATH'' y ''$TERM'', sin que se los debas especificar obligatoriamente.+''$LANG'' con el valor ''es_ES'', fish recibirá tal configuración. Y cualquier emulador que inicies al cual le otorgues variables también las pasarán, a no ser que específicamente decidas no hacerlo. Esta es la manera en la cual fish recibe usualmente los valores de ''$LANG'', ''$PATH'' y ''$TERM'', sin que se los debas especificar obligatoriamente.
  
 Las variables exportadas pueden ser locales, globales o universales; "exportar" no es limitado! Usualmente las querrías globalizar con **set -gx MiVariable AlgunValor**. Las variables exportadas pueden ser locales, globales o universales; "exportar" no es limitado! Usualmente las querrías globalizar con **set -gx MiVariable AlgunValor**.
Línea 320: Línea 316:
 Esto es similar a una expansión arbolada. Esto es similar a una expansión arbolada.
  
-==== Command Substitutions ====+==== Sustitución de Comandos ====
  
-Command substitutions use the output of one command as an argument to anotherUnlike other shells, fish does not use backticks `` for command substitutionsInstead, it uses parentheses with or without a dollar:+La sustitución de comandos utiliza la salida de un comando como argumento de otroA diferencia de otras shells, Fish no utiliza comillas francesas abiertas ''``'' para sustituir comandosEn lugar de ellas utiliza ''()'' con o sin el signo ''$'':
  
 <code bash> <code bash>
Línea 329: Línea 325:
 </code> </code>
  
-A common idiom is to capture the output of a command in a variable:+Un uso común consiste en capturar la salida de un comando en una variable:
  
 <code bash> <code bash>
 set os (uname) set os (uname)
  
-echo $os+echo $so
 Linux Linux
 </code> </code>
  
-Command substitutions without a dollar are not expanded within quotesso the version with a dollar is simpler:+Las sustituciones de comandos que no usen el signo ''$'' resultan expandidas dentro de las encomillado con ''""''de modo que hacerlo con ''$'' resulta más sencillo:
  
 <code bash> <code bash>
Línea 347: Línea 343:
 </code> </code>
  
-Unlike other shells, fish does not split command substitutions on any whitespace (like spaces or tabs), only newlinesThis can be an issue with commands like pkg-config that print what is meant to be multiple arguments on a single lineTo split it on spaces toouse string split.+A diferencia de otras shells, fish no divide la sustitución de comandos o ningún //espacio en blanco// (tales como espacios o tabulaciones), sino nuevas líneasEsto podría implicar dificultades con algunos comandos tales como **pkg-config**, el cual presenta lo que deben ser múltiples argumentos, como una única líneaPara dividirlo a lo largo de los //espacios en blanco// tambiénemplea división de cadenas.
  
 <code bash> <code bash>
Línea 359: Línea 355:
 </code> </code>
  
-If you need a command substitutions output as one argument, without any splits, use quoted command substitution: +Si requieres una salida de sustitución de comandos como un argumento (sin división alguna) utiliza una sustitución de comandos entrecomillada con ''""'':
 <code bash> <code bash>
-echo "first line +echo "primera línea 
-second line" > myfile+segunda línea" > mifichero
  
-set myfile "$(cat myfile)"+set mifichero "$(cat mifichero)"
  
-printf '|%s|' $myfile +printf '|%s|' $mifichero 
-|first line +|primera línea 
-second line|+segunda linea|
 </code> </code>
- 
-For more, see Command substitution. 
  
 ==== Separar comandos (;) ==== ==== Separar comandos (;) ====
Línea 383: Línea 376:
 echo ¡fish; echo es un pescado echo ¡fish; echo es un pescado
  
-or+o
 echo fish echo fish
 echo es un pescado! echo es un pescado!
 </code> </code>
  
-==== Exit Status ====+==== Status de salida ====
  
  
Línea 425: Línea 418:
 </code> </code>
  
-==== Conditionales (If, Else, Switch) ====+==== Condicionales (If, Else, Switch) ====
  
  
Línea 435: Línea 428:
 else if grep bash /etc/shells else if grep bash /etc/shells
     echo "¡Pesqué un bash!"     echo "¡Pesqué un bash!"
 +else if grep ksh /etc/shells
 +    echo "¡Me pesqué un korn-alito!"
 else else
-    echo "No pesqué nada interesante."+    echo "No pesqué shells interesantes."
 end end
 </code> </code>
Línea 443: Línea 438:
  
 <code bash> <code bash>
-if test "$fish" = "flounder+if test "$fish" = "cornalito
-    echo FLOUNDER+    echo CORNALITO
 end end
  
-or+o
  
-if test "$number" -gt 5 +if test "$numero" -gt 5 
-    echo $number es mayor que cinco+    echo $cantidad es mayor que cinco
 else else
-    echo $number es cinco o menor+    echo $cantidad es cinco o menor
 end end
  
Línea 493: Línea 488:
 Como ves, **case** no falla, y puede aceptar argumentos múltiples o comodines entrecomillados con ''"''. Como ves, **case** no falla, y puede aceptar argumentos múltiples o comodines entrecomillados con ''"''.
  
-===== Functions =====+===== Funciones incorporadas =====
  
- +En fish, una función consiste en una lista de comandos, que podrían recibir opcionalmente argumentosA diferencia de otros shells, estos argumentos no resultarán enviados en forma de "variables numeradas" tal como ''$1''sino que en vez de ellos lo serán en forma de una lista única tal como ''$argv''Para crear una función de este tipoutiliza la función incorporada **function**:
-fish function is a list of commandswhich may optionally take argumentsUnlike other shells, arguments are not passed in “numbered variables” like $1, but instead in a single list $argv. To create a functionuse the function builtin:+
  
 <code bash> <code bash>
-function say_hello +function di_hola 
-    echo Hello $argv+    echo Hola $argv
 end end
-say_hello +say_hola 
-printsHello +presentaHola 
-say_hello everybody+di_hola texto-plano.xyz
-printsHello everybody!+PresentaHola texto-plano.xyz!
 </code> </code>
  
-Unlike other shells, fish does not have aliases or special prompt syntaxFunctions take their place2+A diferencia de otras shells, fish no tiene una sintaxis de //prompt// especialLas funciones toman su lugar.
  
-You can list the names of all functions with the functions builtin (note the plural!). fish starts out with a number of functions: 
  
-=== functions ===+Podrás listar el nombre de todas las funciones del intérprete con el comando **functions** incorporado (__¡en plural!__). fish cuenta con una buena cantidad de funciones incorporadas:
  
-N_, abbr, alias, bg, cd, cdh, contains_seq, dirh, dirs, disown, down-or-search, edit_command_buffer, export, fg, fish_add_path, fish_breakpoint_prompt, fish_clipboard_copy, fish_clipboard_paste, fish_config, fish_default_key_bindings, fish_default_mode_prompt, fish_git_prompt, fish_hg_prompt, fish_hybrid_key_bindings, fish_indent, fish_is_root_user, fish_job_summary, fish_key_reader, fish_md5, fish_mode_prompt, fish_npm_helper, fish_opt, fish_print_git_action, fish_print_hg_root, fish_prompt, fish_sigtrap_handler, fish_svn_prompt, fish_title, fish_update_completions, fish_vcs_prompt, fish_vi_cursor, fish_vi_key_bindings, funced, funcsave, grep, help, history, hostname, isatty, kill, la, ll, ls, man, nextd, open, popd, prevd, prompt_hostname, prompt_pwd, psub, pushd, realpath, seq, setenv, suspend, trap, type, umask, up-or-search, vared, wait+=== funciones incorporadas ===
  
-You can see the source for any function by passing its name to functions:+//N_//, //abbr//, //alias//, //bg//, //cd//, //cdh//, //contains_seq//, //dirh//, //dirs//, //disown//, //down-or-search//, //edit_command_buffer//, //export//, //fg//, //fish_add_path//, //fish_breakpoint_prompt//, //fish_clipboard_copy//, //fish_clipboard_paste//, //fish_config//, //fish_default_key_bindings//, //fish_default_mode_prompt//, //fish_git_prompt//, //fish_hg_prompt//, //fish_hybrid_key_bindings//, //fish_indent//, //fish_is_root_user//, //fish_job_summary//, //fish_key_reader//, //fish_md5//, //fish_mode_prompt//, //fish_npm_helper//, //fish_opt//, //fish_print_git_action//, //fish_print_hg_root//, //fish_prompt//, //fish_sigtrap_handler//, //fish_svn_prompt//, //fish_title//, //fish_update_completions//, //fish_vcs_prompt//, //fish_vi_cursor//, //fish_vi_key_bindings//, //funced//, //funcsave//, //grep//, //help//, //history//, //hostname//, //isatty//, //kill//, //la//, //ll//, //ls//, //man//, //nextd//, //open//, //popd//, //prevd//, //prompt_hostname//, //prompt_pwd//, //psub//, //pushd//, //realpath//, //seq//, //setenv//, //suspend//, //trap//, //type//, //umask//, //up-or-search//, //vared//, //wait//. 
 + 
 +Podrás ver el origen de cualquiera de las funciones pasando su nombre a funcions:
  
 <code bash> <code bash>
 functions ls functions ls
-function ls --description 'List contents of directory'+function ls --description 'Lista el contenido de un directorio'
     command ls -G $argv     command ls -G $argv
 end end
 </code> </code>
  
-For more, see Functions. 
- 
-2 
  
-    There is a function called alias, but it’s just a shortcut to make functions.+> Existe una función llamada //alias//pero sólo es un atajo para hacer funciones.
  
 ==== Bucles ==== ==== Bucles ====
Línea 566: Línea 558:
  
  
-Unlike other shells, there is no prompt variable like PS1. To display your prompt, fish executes the fish_prompt function and uses its output as the prompt. And if it existsfish also executes the fish_right_prompt function and uses its output as the right prompt.+A diferencia de otras shells, mno existe una variable para //prompt// tal como ''PS1''Para presentar tu //prompt//, fish ejecuta la función ''fish_prompt'' y emplea su salida como //prompt//Fish también ejecuta la función ''fish_right_prompt'' en caso de existiry usa su salida a la derecha del //prompt//.
  
-You can define your own prompt from the command line:+Podrás definir tu propio //prompt// directamente desde la línea de comandos:
  
 <code bash> <code bash>
-function fish_prompt; echo "New Prompt % "; end+function fish_prompt; echo "Prompt nuevo % "; end
 New Prompt % _ New Prompt % _
 </code> </code>
  
-Thenif you are happy with ityou can save it to disk by typing funcsave fish_prompt. This saves the prompt in ~/.config/fish/functions/fish_prompt.fish. (Orif you wantyou can create that file manually from the start.)+En tal casosi estas satisfecho con este promptpodrás guardarlo en el disco tipeando **funcsave fish_prompt**Esto salvará el prompt en ''~/.config/fish/functions/fish_prompt.fish''. (Osi lo deseaspuedes crear el fichero manualmente desde el comienzo).
  
-Multiple lines are OKColors can be set via set_color, passing it named ANSI colorsor hex RGB values:+Están permitidas utilizar prompts de múltiples líneasPodrás configurarle colores a través de ''set_color''pasándole nombres ANSI de coloreso valores RGB en hexadecimal:
  
 <code bash> <code bash>
Línea 588: Línea 580:
 </code> </code>
  
-This prompt would look like:+Este prompt resultará en:
  
 <code bash> <code bash>
 02/06/13 02/06/13
-/home/tutorial > _+/home/fulana > _
 </code> </code>
  
-You can choose among some sample prompts by running fish_config for a web UI or fish_config prompt for a simpler version inside your terminal.+Puedes escoger entre varios prompts de ejemplo ejecutando **fish_config prompt** o bien **fish_config** desde una interfaz web local.
  
 ==== $PATH ==== ==== $PATH ====
  
  
-$PATH is an environment variable containing the directories that fish searches for commandsUnlike other shells, ''$PATH'' is a listnot a colon-delimited string.+''$PATH'' es una variable de ambiente que contiene los directorios en los cuales Fish buscará los comandos que introduzcasA diferencia de otras shells, ''$PATH'' es una listano una cadena delimitadas por comas '',''.
  
-Fish takes care to set $PATH to a defaultbut typically it is just inherited from fish’s parent process and is set to a value that makes sense for the system - see Exports.+Fish se encargará de definir ''$PATH'' por defectopero típicamente sólo heredará el ''$PATH'' del proceso padre y lo configurará como valor que cobre sentido para el sistema (ver [[#exportar|exportar]]).
  
-To prepend ''/usr/local/bin'' and ''/usr/sbin'' to ''$PATH'', you can write:+Para prefijar ''/usr/local/bin'' ''/usr/sbin'' al ''$PATH'', puedes introducir:
  
 <code bash>set PATH /usr/local/bin /usr/sbin $PATH</code> <code bash>set PATH /usr/local/bin /usr/sbin $PATH</code>
  
-To remove ''/usr/local/bin'' from ''$PATH'', you can write:+Para remover ''/usr/local/bin'' del ''$PATH'', ypuedes introducir:
  
 <code bash>set PATH (string match -v /usr/local/bin $PATH)</code> <code bash>set PATH (string match -v /usr/local/bin $PATH)</code>
  
-For compatibility with other shells and external commands, ''$PATH'' is a path variable, and so will be joined with colons (not spaceswhen you quote it: +Por razones de compatibilidad con otras shell y comandos externosel ''$PATH'' es una variable de rutay de tal modo resultará unida con comas (no espacioscuando lo cites entrecomillado con ''""''
 <code bash> <code bash>
 echo "$PATH" echo "$PATH"
Línea 619: Línea 610:
 </code> </code>
  
-and it will be exported like thatand when fish starts it splits the $PATH it receives into a list on colon.+...de este será exportado de dicha maneray cuando Fish comience dividirá el ''$PATH'' que recibe en forma de lista dividida por '',''.
  
-You can do so directly in config.fish, like you might do in other shells with .profile. See this example.+Puedes hacerlo directamente en ''[[config.fish]]''como harías con otras shells con fichero ''[[.profile]]''.
  
-A faster way is to use the fish_add_path functionwhich adds given directories to the path if they aren’t already includedIt does this by modifying the $fish_user_paths universal variablewhich is automatically prepended to $PATH. For exampleto permanently add /usr/local/bin to your $PATH, you could write:+Una manera más rápida es usar la función ''fish_add_path''que agrega un directorio dato al ''$PATH'' si no estuviese incluída yaEsto lo logra modificando la variable universal ''$fish_user_paths'' la cual será prefijada automáticamente al ''$PATH''Por ejemplopara agregar de forma permanente ''/usr/local/bin'' a tu ''$PATH''introduce:
  
 <code bash>fish_add_path /usr/local/bin</code> <code bash>fish_add_path /usr/local/bin</code>
  
-The advantage is that you don’t have to go mucking around in files: just run this once at the command lineand it will affect the current session and all future instances tooYou can also add this line to config.fish, as it only adds the component if necessary.+La ventaja reside en que no tendrás que ir editando ficheros de confuración. Simplemente escribe esto una vez en la línea de comandosy afectará tanto la sesión actual como todas las instancias futurasTambién puedes agregar esta línea al ''[[config.fish]]''ya que solo agregará el componente si es necesario hacerlo.
  
-Or you can modify $fish_user_paths yourselfbut you should be careful not to append to it unconditionally in config.fish, or it will grow longer and longer. +O puedes modicar ''$fish_user_paths'' por tí mismopero debes ser cuidadoso de no agregarlo incondicionalmente al''config.fish''o crecerá más y más grande.
-Startup (Where’s .bashrc?)+
  
-Fish starts by executing commands in ''~/.config/fish/config.fish''. You can create it if it does not exist.+==== Inicio (¿dónde está .bashrc?) ====
  
-It is possible to directly create functions and variables in config.fish file, using the commands shown aboveFor example:+Fish inicia ejecutando los comandos dispuestos en ''~/.config/fish/[[config.fish]]''. Puedes crear este fichero si no existe. 
 + 
 +Es posible crear firectamente funciones y variables para el ''config.fish'' utilizando los comandos mostrados arribaPor ejemplo:
  
 <code bash> <code bash>
Línea 646: Línea 638:
 </code> </code>
  
-Howeverit is more common and efficient to use autoloading functions and universal variables.+Sin embargolo más eficiente y común es usar funciones de autocargado y variables univeresales.
  
-If you want to organize your configuration, fish also reads commands in ''.fish'' files in ''~/.config/fish/conf.d/''. See Configuration Files for the details+>Si deseas organizar tus configuraciones, fish también lee los comandos en los ficheros de extensión ''.fish'' situados en ''~/.config/fish/conf.d/''
-==== Autoloading Functions ====+==== Funciones de Autocarga ====
  
  
-When fish encounters a commandit attempts to autoload a function for that commandby looking for a file with the name of that command in ''~/.config/fish/functions/''.+Cuando fish encuentra un comandointenta autocargar una función con dicho nombre de comandobuscando un fichero con tal nombre o un comando situado en ''~/.config/fish/functions/''.
  
-For exampleif you wanted to have a function ll, you would add a text file ll.fish to ''~/.config/fish/functions'':+Por ejemplosi deseas tener una función llamada ''ll''agregarías un fichero de texto llamado ''ll.fish''''~/.config/fish/functions'':
  
 <code bash> <code bash>
Línea 663: Línea 655:
 </code> </code>
  
-This is the preferred way to define your prompt as well:+Esta es también la manera preferida de definir tu //prompt// en Fish:
  
 <code bash> <code bash>
Línea 671: Línea 663:
 end end
 </code> </code>
 +==== Variables Universales ====
  
-See the documentation for funced and funcsave for ways to create these files automatically, and ''$fish_function_path'' to control their location. +Una variable universal es una variable cuyo valor es compartido por todas las instancias de fish, ahora y en el futuro (incluso ante un reinicio)Si administras el sistema, podrías hacer universal una variable con **set -U**:
- +
-==== Universal Variables ==== +
- +
-universal variable is a variable whose value is shared across all instances of fish, now and in the future – even after a rebootYou can make a variable universal with ''set -U'':+
  
 <code bash> <code bash>
-set -U EDITOR vim+set -U EDITOR nano 
 +</code>
  
-Now in another shell:+Ahora, en otra shell:
  
 +<code bash>
 echo $EDITOR echo $EDITOR
-vim+nano
 </code> </code>
 +
 +===== Conclusión =====
 +
 +Has aprendido las grandes diferencias puntuales del shell Fish. ¡Felicitaciones!
  • tutorial_de_fish.1656451251.txt.gz
  • Última modificación: 2022/06/28 21:20
  • por peron