Ambos lados, revisión anterior Revisión previa Próxima revisión | Revisión previaÚltima revisiónAmbos lados, revisión siguiente |
tutorial_de_fish [2022/06/28 22:21] – [Functions] peron | tutorial_de_fish [2022/07/05 20:14] – [Conditionales (If, Else, Switch)] peron |
---|
| |
==== 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> |
| |
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** o **-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**. |
set os (uname) | set os (uname) |
| |
echo $os | echo $so |
Linux | Linux |
</code> | </code> |
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> |
| |
==== Conditionales (If, Else, Switch) ==== | ==== Condicionales (If, Else, Switch) ==== |
| |
| |
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> |
| |
<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 |
| |
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 ''"''. |
| |
===== Funciones ===== | ===== Funciones incorporadas ===== |
| |
Una función de fish es una lista de comandos, que podrían tomar argumentos opcionales. A diferencia de otros shells, los argumentos no son pasados en forma de "variables numeradas" tal como ''$1'', sino que en vez de ellos lo son en una lista única como ''$argv''. Para crear una función, utiliza la función incorporada: | En fish, una función consiste en una lista de comandos, que podrían recibir opcionalmente argumentos. A 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 tipo, utiliza la función incorporada **function**: |
| |
<code bash> | <code bash> |
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: | 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: |
| |
=== funcciones === | === 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 | 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 |
| |
| |
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 exists, fish 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 existir, y 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> |
| |
Then, if you are happy with it, you can save it to disk by typing funcsave fish_prompt. This saves the prompt in ~/.config/fish/functions/fish_prompt.fish. (Or, if you want, you can create that file manually from the start.) | En tal caso, si estas satisfecho con este prompt, podrás guardarlo en el disco tipeando **funcsave fish_prompt**. Esto salvará el prompt en ''~/.config/fish/functions/fish_prompt.fish''. (O, si lo deseas, puedes crear el fichero manualmente desde el comienzo). |
| |
Multiple lines are OK. Colors can be set via set_color, passing it named ANSI colors, or hex RGB values: | Están permitidas utilizar prompts de múltiples líneas. Podrás configurarle colores a través de ''set_color'', pasándole nombres ANSI de colores, o valores RGB en hexadecimal: |
| |
<code bash> | <code bash> |
</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 commands. Unlike other shells, ''$PATH'' is a list, not a colon-delimited string. | ''$PATH'' es una variable de ambiente que contiene los directorios en los cuales Fish buscará los comandos que introduzcas. A diferencia de otras shells, ''$PATH'' es una lista, no una cadena delimitadas por comas '',''. |
| |
Fish takes care to set $PATH to a default, but 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 defecto, pero 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'' y ''/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 spaces) when you quote it: | Por razones de compatibilidad con otras shell y comandos externos, el ''$PATH'' es una variable de ruta, y de tal modo resultará unida con comas (no espacios) cuando lo cites entrecomillado con ''""'' |
<code bash> | <code bash> |
echo "$PATH" | echo "$PATH" |
</code> | </code> |
| |
and it will be exported like that, and when fish starts it splits the $PATH it receives into a list on colon. | ...de este será exportado de dicha manera, y 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 function, which adds given directories to the path if they aren’t already included. It does this by modifying the $fish_user_paths universal variable, which is automatically prepended to $PATH. For example, to 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 ya. Esto lo logra modificando la variable universal ''$fish_user_paths'' , la cual será prefijada automáticamente al ''$PATH''. Por ejemplo, para 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 line, and it will affect the current session and all future instances too. You 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 comandos, y afectará tanto la sesión actual como todas las instancias futuras. Tambié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 yourself, but 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í mismo, pero 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 above. For 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 arriba. Por ejemplo: |
| |
<code bash> | <code bash> |
</code> | </code> |
| |
However, it is more common and efficient to use autoloading functions and universal variables. | Sin embargo, lo 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 command, it attempts to autoload a function for that command, by looking for a file with the name of that command in ''~/.config/fish/functions/''. | Cuando fish encuentra un comando, intenta autocargar una función con dicho nombre de comando, buscando un fichero con tal nombre o un comando situado en ''~/.config/fish/functions/''. |
| |
For example, if you wanted to have a function ll, you would add a text file ll.fish to ''~/.config/fish/functions'': | Por ejemplo, si deseas tener una función llamada ''ll'', agregarías un fichero de texto llamado ''ll.fish'' a ''~/.config/fish/functions'': |
| |
<code bash> | <code bash> |
</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> |
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 ==== | |
| |
A universal variable is a variable whose value is shared across all instances of fish, now and in the future – even after a reboot. You 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! |