Terminal (1/3): navegación, archivos y comandos

Terminal (1/3): navegación, archivos y comandos

📚 **Esta entrada es parte de la serie _Introducción a la terminal_**, dividida en tres capítulos que se leen en orden:

> * 👉 **Parte 1: Navegación, archivos y comandos**

* Parte 2: Red, compresión y procesos

* Parte 3: Administración del sistema

Formato del postlink image 1

Para no tener que estar poniendo imágenes de la consola en cada acción que haga, he creado la siguiente función que recibe el comando de la terminal que queramos ejecutar y devuelve la salida que nos daría la terminal.

Unas veces usaré esta función, y otras usaré ! antes de cada comando, que en notebooks quiere decir que vas a ejecutar un comando de la terminal.

	
< > Input
Python
import subprocess
import os
last_directory = ''
def terminal(command, max_lines_output=None):
global last_directory
debug = False
str = command.split()
# Check if there are " or ' characters
for i in range(len(str)):
if debug: print(f"i = {i}, str[i] = {str[i]}")
if len(str[i]) &gt; 0:
if str[i][0] == '"' or str[i][0] == "'":
for j in range(i+1,len(str)):
if debug: print(f" j = {j}, str[j] = {str[j]}")
if str[j][-1] == '"' or str[j][-1] == "'":
for k in range(i+1,j+1):
if debug: print(f" k = {k}, str[i] = {str[i]}, str[k] = {str[k]}")
str[i] = str[i] + " " + str[k]
if debug: print(f" k = {k}, str[i] = {str[i]}, str[k] = {str[k]}")
str[j:] = [""]
str[i] = str[i].replace('"','')
# Remove empty strings
str = [x for x in str if x != ""]
if debug:
print(str)
return
if str[0] == "cd":
last_dir = os.getcwd()
if len(str) == 1:
os.chdir('/home/wallabot')
else:
if str[1] == "-":
os.chdir(last_directory)
else:
os.chdir(str[1])
last_directory = last_dir
else:
result = subprocess.run(str, stdout=subprocess.PIPE).stdout.decode('utf-8')
if max_lines_output is not None:
result_split = result.split(' ')
print(' '.join(result_split[:max_lines_output]))
print(" ...")
print(' '.join(result_split[-5:]))
else:
print(result)
Copied

Primeros comandos para moverse por la terminallink image 2

ls (list directory)link image 3

El primer comando que vamos a ver es ls (list directory), que sirve para listar todos los archivos de la carpeta en la que estemos.

	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
__pycache__
ssh.ipynb
test.html
test.ipynb

Los comandos normalmente pueden recibir opciones (flags), que se introducen con el carácter -, por ejemplo, veamos ls -l que nos devuelve la lista de archivos del directorio en el que estamos, pero con más información

	
< > Input
Python
terminal('ls -l')
Copied
>_ Output
			
total 4512
-rw-rw-r-- 1 wallabot wallabot 285898 nov 12 02:07 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 78450 nov 13 00:10 2021-04-23-Calculo-matricial-con-Numpy.ipynb
-rw-rw-r-- 1 wallabot wallabot 484213 nov 13 00:44 2021-06-15-Manejo-de-datos-con-Pandas.ipynb
-rw-rw-r-- 1 wallabot wallabot 320810 dic 6 00:11 2022-09-12 Introduccion a la terminal.ipynb
-rw-rw-r-- 1 wallabot wallabot 320594 dic 6 00:04 2022-09-12 Introduccion a la terminal.txt
-rw-rw-r-- 1 wallabot wallabot 119471 oct 3 16:13 command-line-cheat-sheet.pdf
-rw-rw-r-- 1 wallabot wallabot 2660 sep 18 03:32 CSS.ipynb
-rw-rw-r-- 1 wallabot wallabot 699225 nov 27 04:16 Docker.html
-rw-rw-r-- 1 wallabot wallabot 509125 sep 22 16:48 Docker.ipynb
-rw-rw-r-- 1 wallabot wallabot 156193 nov 27 04:21 Expresiones regulares.html
-rw-rw-r-- 1 wallabot wallabot 53094 oct 2 04:57 Expresiones regulares.ipynb
drwxrwxr-x 2 wallabot wallabot 4096 nov 28 14:39 html_files
-rw-rw-r-- 1 wallabot wallabot 14775 sep 18 03:29 html.ipynb
drwxrwxr-x 3 wallabot wallabot 4096 nov 12 01:51 introduccion_python
-rw-rw-r-- 1 wallabot wallabot 446172 oct 2 04:39 movies.csv
-rw-rw-r-- 1 wallabot wallabot 522197 oct 2 04:33 movies.dat
drwxrwxr-x 2 wallabot wallabot 4096 nov 28 14:39 notebooks_translated
drwxrwxr-x 2 wallabot wallabot 4096 ago 27 03:25 __pycache__
-rw-rw-r-- 1 wallabot wallabot 586 dic 4 02:31 ssh.ipynb
-rw-rw-r-- 1 wallabot wallabot 292936 nov 9 01:46 test.html
-rw-rw-r-- 1 wallabot wallabot 260227 nov 9 01:13 test.ipynb

Como vemos, tenemos cuántos bytes ocupa cada archivo, pero cuando tenemos archivos que ocupan mucho, esto no es muy fácil de leer, así que podemos añadir la opción h (human) que nos da información más fácil de leer

	
< > Input
Python
terminal('ls -lh')
Copied
>_ Output
			
total 4,5M
-rw-rw-r-- 1 wallabot wallabot 280K nov 12 02:07 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 77K nov 13 00:10 2021-04-23-Calculo-matricial-con-Numpy.ipynb
-rw-rw-r-- 1 wallabot wallabot 473K nov 13 00:44 2021-06-15-Manejo-de-datos-con-Pandas.ipynb
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:11 2022-09-12 Introduccion a la terminal.ipynb
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:04 2022-09-12 Introduccion a la terminal.txt
-rw-rw-r-- 1 wallabot wallabot 117K oct 3 16:13 command-line-cheat-sheet.pdf
-rw-rw-r-- 1 wallabot wallabot 2,6K sep 18 03:32 CSS.ipynb
-rw-rw-r-- 1 wallabot wallabot 683K nov 27 04:16 Docker.html
-rw-rw-r-- 1 wallabot wallabot 498K sep 22 16:48 Docker.ipynb
-rw-rw-r-- 1 wallabot wallabot 153K nov 27 04:21 Expresiones regulares.html
-rw-rw-r-- 1 wallabot wallabot 52K oct 2 04:57 Expresiones regulares.ipynb
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 html_files
-rw-rw-r-- 1 wallabot wallabot 15K sep 18 03:29 html.ipynb
drwxrwxr-x 3 wallabot wallabot 4,0K nov 12 01:51 introduccion_python
-rw-rw-r-- 1 wallabot wallabot 436K oct 2 04:39 movies.csv
-rw-rw-r-- 1 wallabot wallabot 510K oct 2 04:33 movies.dat
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 notebooks_translated
drwxrwxr-x 2 wallabot wallabot 4,0K ago 27 03:25 __pycache__
-rw-rw-r-- 1 wallabot wallabot 586 dic 4 02:31 ssh.ipynb
-rw-rw-r-- 1 wallabot wallabot 287K nov 9 01:46 test.html
-rw-rw-r-- 1 wallabot wallabot 255K nov 9 01:13 test.ipynb

Si queremos ver los archivos ocultos, podemos usar la opción a, que nos mostrará todos los archivos de un directorio.

	
< > Input
Python
terminal('ls -lha')
Copied
>_ Output
			
total 4,5M
drwxrwxr-x 6 wallabot wallabot 4,0K dic 6 00:04 .
drwxrwxr-x 5 wallabot wallabot 4,0K oct 2 03:10 ..
-rw-rw-r-- 1 wallabot wallabot 280K nov 12 02:07 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 77K nov 13 00:10 2021-04-23-Calculo-matricial-con-Numpy.ipynb
-rw-rw-r-- 1 wallabot wallabot 473K nov 13 00:44 2021-06-15-Manejo-de-datos-con-Pandas.ipynb
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:11 2022-09-12 Introduccion a la terminal.ipynb
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:04 2022-09-12 Introduccion a la terminal.txt
-rw-rw-r-- 1 wallabot wallabot 117K oct 3 16:13 command-line-cheat-sheet.pdf
-rw-rw-r-- 1 wallabot wallabot 2,6K sep 18 03:32 CSS.ipynb
-rw-rw-r-- 1 wallabot wallabot 683K nov 27 04:16 Docker.html
-rw-rw-r-- 1 wallabot wallabot 498K sep 22 16:48 Docker.ipynb
-rw-rw-r-- 1 wallabot wallabot 153K nov 27 04:21 Expresiones regulares.html
-rw-rw-r-- 1 wallabot wallabot 52K oct 2 04:57 Expresiones regulares.ipynb
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 html_files
-rw-rw-r-- 1 wallabot wallabot 15K sep 18 03:29 html.ipynb
drwxrwxr-x 3 wallabot wallabot 4,0K nov 12 01:51 introduccion_python
-rw-rw-r-- 1 wallabot wallabot 436K oct 2 04:39 movies.csv
-rw-rw-r-- 1 wallabot wallabot 510K oct 2 04:33 movies.dat
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 notebooks_translated
drwxrwxr-x 2 wallabot wallabot 4,0K ago 27 03:25 __pycache__
-rw-rw-r-- 1 wallabot wallabot 586 dic 4 02:31 ssh.ipynb
-rw-rw-r-- 1 wallabot wallabot 287K nov 9 01:46 test.html
-rw-rw-r-- 1 wallabot wallabot 255K nov 9 01:13 test.ipynb

Si lo que queremos es que nos los ordene por tamaño, podemos usar la opción S

	
< > Input
Python
terminal('ls -lhS')
Copied
>_ Output
			
total 4,5M
-rw-rw-r-- 1 wallabot wallabot 683K nov 27 04:16 Docker.html
-rw-rw-r-- 1 wallabot wallabot 510K oct 2 04:33 movies.dat
-rw-rw-r-- 1 wallabot wallabot 498K sep 22 16:48 Docker.ipynb
-rw-rw-r-- 1 wallabot wallabot 473K nov 13 00:44 2021-06-15-Manejo-de-datos-con-Pandas.ipynb
-rw-rw-r-- 1 wallabot wallabot 436K oct 2 04:39 movies.csv
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:11 2022-09-12 Introduccion a la terminal.ipynb
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:04 2022-09-12 Introduccion a la terminal.txt
-rw-rw-r-- 1 wallabot wallabot 287K nov 9 01:46 test.html
-rw-rw-r-- 1 wallabot wallabot 280K nov 12 02:07 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 255K nov 9 01:13 test.ipynb
-rw-rw-r-- 1 wallabot wallabot 153K nov 27 04:21 Expresiones regulares.html
-rw-rw-r-- 1 wallabot wallabot 117K oct 3 16:13 command-line-cheat-sheet.pdf
-rw-rw-r-- 1 wallabot wallabot 77K nov 13 00:10 2021-04-23-Calculo-matricial-con-Numpy.ipynb
-rw-rw-r-- 1 wallabot wallabot 52K oct 2 04:57 Expresiones regulares.ipynb
-rw-rw-r-- 1 wallabot wallabot 15K sep 18 03:29 html.ipynb
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 html_files
drwxrwxr-x 3 wallabot wallabot 4,0K nov 12 01:51 introduccion_python
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 notebooks_translated
drwxrwxr-x 2 wallabot wallabot 4,0K ago 27 03:25 __pycache__
-rw-rw-r-- 1 wallabot wallabot 2,6K sep 18 03:32 CSS.ipynb
-rw-rw-r-- 1 wallabot wallabot 586 dic 4 02:31 ssh.ipynb

Si queremos que nos muestre los archivos ordenados alfabéticamente, pero al revés, debemos usar la opción -r

	
< > Input
Python
terminal('ls -lhr')
Copied
>_ Output
			
total 4,5M
-rw-rw-r-- 1 wallabot wallabot 255K nov 9 01:13 test.ipynb
-rw-rw-r-- 1 wallabot wallabot 287K nov 9 01:46 test.html
-rw-rw-r-- 1 wallabot wallabot 586 dic 4 02:31 ssh.ipynb
drwxrwxr-x 2 wallabot wallabot 4,0K ago 27 03:25 __pycache__
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 notebooks_translated
-rw-rw-r-- 1 wallabot wallabot 510K oct 2 04:33 movies.dat
-rw-rw-r-- 1 wallabot wallabot 436K oct 2 04:39 movies.csv
drwxrwxr-x 3 wallabot wallabot 4,0K nov 12 01:51 introduccion_python
-rw-rw-r-- 1 wallabot wallabot 15K sep 18 03:29 html.ipynb
drwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 html_files
-rw-rw-r-- 1 wallabot wallabot 52K oct 2 04:57 Expresiones regulares.ipynb
-rw-rw-r-- 1 wallabot wallabot 153K nov 27 04:21 Expresiones regulares.html
-rw-rw-r-- 1 wallabot wallabot 498K sep 22 16:48 Docker.ipynb
-rw-rw-r-- 1 wallabot wallabot 683K nov 27 04:16 Docker.html
-rw-rw-r-- 1 wallabot wallabot 2,6K sep 18 03:32 CSS.ipynb
-rw-rw-r-- 1 wallabot wallabot 117K oct 3 16:13 command-line-cheat-sheet.pdf
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:04 2022-09-12 Introduccion a la terminal.txt
-rw-rw-r-- 1 wallabot wallabot 314K dic 6 00:11 2022-09-12 Introduccion a la terminal.ipynb
-rw-rw-r-- 1 wallabot wallabot 473K nov 13 00:44 2021-06-15-Manejo-de-datos-con-Pandas.ipynb
-rw-rw-r-- 1 wallabot wallabot 77K nov 13 00:10 2021-04-23-Calculo-matricial-con-Numpy.ipynb
-rw-rw-r-- 1 wallabot wallabot 280K nov 12 02:07 2021-02-11-Introduccion-a-Python.ipynb

cd (change directory)link image 4

El segundo comando será cd (change directory) que nos permite cambiar de directorio

	
< > Input
Python
terminal('cd /home/wallabot/Documentos/')
Copied

Si ahora volvemos a usar ls para ver los archivos que tenemos, vemos que cambian

	
< > Input
Python
terminal('ls')
Copied
>_ Output
			
aprendiendo-git.pdf
balena-etcher-electron-1.7.9-linux-x64
camerasIP
Documentacion
gstreamer
gstreamer_old
jetsonNano
kaggle
Libros
nerf
prueba.txt
pytorch
wallabot
web

Si a cd, en vez de darle el directorio al que nos queremos mover, le damos el carácter -, volverá al anterior directorio donde estaba

	
< > Input
Python
terminal('cd -')
Copied
	
< > Input
Python
terminal('ls')
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
__pycache__
ssh.ipynb
test.html
test.ipynb

Si nos quisiéramos mover a la home introduciendo solamente cd en la terminal nos llevará.

	
< > Input
Python
terminal('cd')
Copied

pwd (print working directory)link image 5

Para obtener el directorio en el que estamos, podemos usar pwd (print working directory)

	
< > Input
Python
terminal('pwd')
Copied
>_ Output
			
/home/wallabot

Podemos movernos mediante el comando cd mediante rutas relativas y mediante rutas absolutas. Por ejemplo, vamos a movernos a un directorio mediante una ruta absoluta.

	
< > Input
Python
terminal('cd /home/wallabot/Documentos/')
Copied
	
< > Input
Python
terminal('pwd')
Copied
>_ Output
			
/home/wallabot/Documentos
	
< > Input
Python
terminal('ls')
Copied
>_ Output
			
aprendiendo-git.pdf
balena-etcher-electron-1.7.9-linux-x64
camerasIP
Documentacion
gstreamer
gstreamer_old
jetsonNano
kaggle
Libros
nerf
prueba.txt
pytorch
wallabot
web

Podemos movernos mediante rutas relativas si solo ponemos la dirección a partir del punto en el que nos encontramos

	
< > Input
Python
terminal('cd web')
Copied
	
< > Input
Python
terminal('pwd')
Copied
>_ Output
			
/home/wallabot/Documentos/web

También mediante rutas relativas podemos ir un directorio arriba mediante ..

	
< > Input
Python
terminal('cd ..')
Copied
	
< > Input
Python
terminal('pwd')
Copied
>_ Output
			
/home/wallabot/Documentos

Si en vez de .. ponemos . nos estamos refiriendo al directorio en el que nos encontramos ahora mismo, es decir, si ponemos cd . no nos moveremos, ya que le estamos diciendo a la terminal que vaya al directorio en el que estamos.

	
< > Input
Python
terminal('cd .')
Copied
	
< > Input
Python
terminal('pwd')
Copied
>_ Output
			
/home/wallabot/Documentos

Vamos a movernos a una ruta en la que tengamos archivos para mostrar el siguiente comando

	
< > Input
Python
terminal('cd web/portafolio/posts/')
Copied
	
< > Input
Python
terminal('ls')
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
__pycache__
ssh.ipynb
test.html
test.ipynb

Información de archivos con filelink image 6

Si yo no sé qué tipo de archivo es alguno en particular, mediante el comando file puedo obtener una descripción

	
< > Input
Python
terminal('file 2021-02-11-Introduccion-a-Python.ipynb')
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb: UTF-8 Unicode text, with very long lines

Manipulando archivos y directorioslink image 7

Movámonos primero a la home.

	
< > Input
Python
terminal('cd /home/wallabot/Documentos/')
Copied

Árbol de directorios con treelink image 8

Podemos ver toda la estructura de la carpeta en la que estamos mediante el comando tree

	
< > Input
Python
terminal('tree', max_lines_output=20)
Copied
>_ Output
			
.
├── aprendiendo-git.pdf
├── balena-etcher-electron-1.7.9-linux-x64
│   └── balenaEtcher-1.7.9-x64.AppImage
├── camerasIP
│   ├── camerasIP.py
│   ├── camerasIP.sh
│   ├── config.py
│   ├── __pycache__
│   │   ├── config.cpython-38.pyc
│   │   └── config.cpython-39.pyc
│   └── README.md
├── Documentacion
│   ├── Curriculum Vitae (5).pdf
│   ├── Firma Pris.PNG
│   └── Firma.png
├── gstreamer
│   ├── basic_tutorial_c
│   │   ├── basic_tutorial_1_hello_world
│   │   │   ├── basic-tutorial-1
...
├── upload_page.py
└── utils.py
873 directories, 119679 files

Pero a la salida tenemos demasiadas líneas, y esto es porque tree es un comando que muestra todos los archivos desde la ruta en la que estamos, por lo que es un poco difícil de leer. Sin embargo, con la opción L podemos indicarle en cuántos niveles queremos que profundice

	
< > Input
Python
terminal('tree -L 2')
Copied
>_ Output
			
.
├── aprendiendo-git.pdf
├── balena-etcher-electron-1.7.9-linux-x64
│   └── balenaEtcher-1.7.9-x64.AppImage
├── camerasIP
│   ├── camerasIP.py
│   ├── camerasIP.sh
│   ├── config.py
│   ├── __pycache__
│   └── README.md
├── Documentacion
│   ├── Curriculum Vitae (5).pdf
│   ├── Firma Pris.PNG
│   └── Firma.png
├── gstreamer
│   ├── basic_tutorial_c
│   └── README.md
├── gstreamer_old
│   ├── basic_tutorial_c
│   └── basic_tutorial_python
...
├── wallabot
│   ├── Microfono - Blue Yeti X
│   ├── placa base - Asus prime x570-p
│   └── Silla - Corsair T3 Rush
└── web
├── jupyter-to-html
├── jupyter-translator
├── portafolio
└── wordpress_api_rest
30 directories, 12 files

Podemos ver que muestra que hay 30 directorios y 12 archivos, mientras que antes indicaba 873 directorios y 119679 archivos

Crear carpetas con mkdir (make directory)link image 9

Si queremos crear un nuevo directorio podemos usar el comando mkdir (make directory) y un nombre

	
< > Input
Python
terminal("cd /home/wallabot/Documentos/web/portafolio/posts/")
Copied
	
< > Input
Python
terminal('mkdir prueba')
Copied
>_ Output
			
	
< > Input
Python
terminal('ls')
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
prueba
__pycache__
ssh.ipynb
test.html
test.ipynb

Si lo que queremos es crear un directorio con espacios en el nombre, tenemos que poner el nombre entre comillas.

	
< > Input
Python
terminal('mkdir "directorio prueba"')
Copied
>_ Output
			
	
< > Input
Python
terminal('ls')
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
directorio prueba
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
prueba
__pycache__
ssh.ipynb
test.html
test.ipynb

Vamos a meternos dentro de la carpeta prueba que hemos creado, para seguir viendo allí la terminal

	
< > Input
Python
terminal("cd prueba")
Copied

Crear archivos con touchlink image 10

En caso de que queramos crear un archivo, el comando que tenemos que usar es touch

	
< > Input
Python
terminal("touch prueba.txt")
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
prueba.txt

Copiar archivos con cp (copy)link image 11

Si queremos copiar un archivo lo hacemos mediante el comando cp (copy)

	
< > Input
Python
terminal("cp prueba.txt prueba_copy.txt")
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
prueba_copy.txt
prueba.txt

Mover archivos con mv (move)link image 12

Si lo que queremos es moverlo, lo que usamos es el comando mv (move)

	
< > Input
Python
terminal("mv prueba.txt ../prueba.txt")
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
prueba_copy.txt
	
< > Input
Python
terminal("ls ../")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
directorio prueba
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
prueba
prueba.txt
__pycache__
ssh.ipynb
test.html
test.ipynb

Renombrar archivos con mv (move)link image 13

El comando mv también nos sirve para renombrar ficheros, ya que si lo que hacemos es moverlo en el mismo directorio, pero dándole otro nombre, al final eso es renombrar el archivo.

	
< > Input
Python
terminal("mv prueba_copy.txt prueba_move.txt")
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
prueba_move.txt

Borrar archivos con rm (remove)link image 14

Para borrar archivos o directorios usamos el comando rm (remove)

	
< > Input
Python
terminal("rm prueba_move.txt")
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			

Eliminar directorios con rm -r (remove recursive)link image 15

Si lo que queremos es eliminar un directorio con archivos dentro, debemos usar el flag -r.

	
< > Input
Python
terminal("cd ..")
Copied
	
< > Input
Python
terminal('rm -r "directorio prueba"')
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
prueba
prueba.txt
__pycache__
ssh.ipynb
test.html
test.ipynb

Como puedes ver nunca pregunta si estamos seguros, para que pregunte hay que añadir el flag -i (interactive)

	
< > Input
Python
terminal("rm -i prueba.txt")
Copied
>_ Output
			
rm: ¿borrar el fichero regular vacío 'prueba.txt'? (s/n) s

Sincronizar archivos mediante rsynclink image 16

Hasta ahora hemos visto cómo copiar, mover y eliminar archivos, pero supongamos que tenemos una carpeta y copiamos esos archivos a otra. Ahora supongamos que modificamos un archivo de la primera carpeta y queremos que la segunda tenga los cambios. Tenemos dos opciones, volver a copiar todos los archivos, o hacer una sincronización mediante rsync

Primero vamos a crear una nueva carpeta en la que creamos varios archivos

	
< > Input
Python
!mkdir sourcefolder
!touch sourcefolder/file1 sourcefolder/file2 sourcefolder/file3
Copied

Ahora creamos una segunda carpeta que es la que vamos a sincronizar con la primera

	
< > Input
Python
!mkdir syncfolder
Copied
	
< > Input
Python
!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolder
Copied
>_ Output
			
ls sourcefolder:
file1 file2 file3
ls syncfolder:

Sincronizamos las dos carpetas con rsync, la primera vez solo copiará los archivos de la primera carpeta a la segunda. Para hacer esto, además debemos añadir el flag -r (recursive)

	
< > Input
Python
!rsync -r sourcefolder/ syncfolder/
Copied
	
< > Input
Python
!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolder
Copied
>_ Output
			
ls sourcefolder:
file1 file2 file3
ls syncfolder:
file1 file2 file3

Si ahora creo un nuevo archivo en sourcefolder y vuelvo a sincronizar, se copia solo ese archivo en syncfolder. Para ver que solo se copia un archivo podemos usar el flag -v (verbose)

	
< > Input
Python
!touch sourcefolder/file4
Copied
	
< > Input
Python
!rsync -r -v sourcefolder/ syncfolder/
Copied
>_ Output
			
sending incremental file list
file1
file2
file3
file4
sent 269 bytes received 92 bytes 722.00 bytes/sec
total size is 0 speedup is 0.00

Pero parece que ha copiado todos los archivos, así que para que esto no pase y copie solo los que se han modificado, hay que usar el flag -u

	
< > Input
Python
!touch sourcefolder/file5
Copied
	
< > Input
Python
!rsync -r -v -u sourcefolder/ syncfolder/
Copied
>_ Output
			
sending incremental file list
file5
sent 165 bytes received 35 bytes 400.00 bytes/sec
total size is 0 speedup is 0.00
	
< > Input
Python
!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolder
Copied
>_ Output
			
ls sourcefolder:
file1 file2 file3 file4 file5
ls syncfolder:
file1 file2 file3 file4 file5

¿Y qué pasa si creo un archivo nuevo en syncfolder?

	
< > Input
Python
!touch syncfolder/file6
Copied
	
< > Input
Python
!rsync -r -v -u sourcefolder/ syncfolder/
Copied
>_ Output
			
sending incremental file list
sent 122 bytes received 12 bytes 268.00 bytes/sec
total size is 0 speedup is 0.00
	
< > Input
Python
!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolder
Copied
>_ Output
			
ls sourcefolder:
file1 file2 file3 file4 file5
ls syncfolder:
file1 file2 file3 file4 file5 file6

No lo sincroniza, así que es importante tenerlo en cuenta

Algunos flags importantes que hay que tener en cuenta son:

  • -a: Este flag es un atajo para varias opciones, incluyendo -r (recursivo), -l (copiar enlaces simbólicos), -p (mantener permisos), -t (mantener la hora de modificación) y -g (mantener grupo). Esta opción es útil para hacer una copia exacta de un directorio, incluyendo todas sus subcarpetas y archivos.
  • -v: Este flag activa la salida detallada, que muestra los archivos que se están copiando y el progreso de la operación.
  • -r: Este flag es utilizado para copiar de forma recursiva, lo que significa que copia todas las subcarpetas y archivos dentro de un directorio.
  • -u: Este flag es utilizado para copiar solo los archivos nuevos o modificados. Si un archivo ya existe en el destino y es más reciente que el archivo de origen, no se copia.
  • -n: Este flag se utiliza para hacer una prueba de copia, lo que significa que no se realizan cambios en el destino.
  • --exclude: Este flag se utiliza para excluir archivos o carpetas específicos de la operación de copia. Puedes especificar varios archivos o carpetas para excluir utilizando esta opción varias veces.
  • -z: Este flag se utiliza para comprimir los datos durante la transferencia, lo que reduce el ancho de banda utilizado y acelera la velocidad de transferencia.
  • -h: este flag se usa para mostrar la información en un formato más legible, especialmente cuando se trabaja con grandes cantidades de datos o tamaños de archivos grandes.

Borramos las dos carpetas creadas

	
< > Input
Python
!rm -r sourcefolder syncfolder
Copied

Explorando el contenido de los archivoslink image 17

Para no tener que abrir un archivo desde una interfaz gráfica tenemos varias formas. Voy a copiar un archivo de texto en esta carpeta lo primero.

	
< > Input
Python
terminal("cd prueba")
Copied
	
< > Input
Python
terminal("cp ../2021-02-11-Introduccion-a-Python.ipynb .")
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb

Cabecera de archivos con headlink image 18

El primer comando para poder ver dentro de un archivo de texto es head, que nos permite ver las primeras 10 líneas de un archivo, pero si se le mete el flag -n puedes indicar el número de líneas

	
< > Input
Python
terminal("head 2021-02-11-Introduccion-a-Python.ipynb")
Copied
>_ Output
			
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "dsaKCKL0IxZl"
},
"source": [
"# Introducción a Python"
]
	
< > Input
Python
terminal("head -n 5 2021-02-11-Introduccion-a-Python.ipynb")
Copied
>_ Output
			
{
"cells": [
{
"cell_type": "markdown",
"metadata": {

Cola de un archivo con taillink image 19

En caso de querer ver las últimas líneas usamos tail

	
< > Input
Python
terminal("tail 2021-02-11-Introduccion-a-Python.ipynb")
Copied
>_ Output
			
},
"vscode": {
"interpreter": {
"hash": "d5745ab6aba164e1152437c779991855725055592b9f2bdb41a4825db7168d26"
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
	
< > Input
Python
terminal("tail -n 5 2021-02-11-Introduccion-a-Python.ipynb")
Copied
>_ Output
			
}
},
"nbformat": 4,
"nbformat_minor": 0
}

Si queremos ver continuamente las últimas líneas de un archivo, por ejemplo, queremos estar monitorizando continuamente un archivo de LOG para ver eventos, añadimos el flag -f, esto hará que la terminal se quede continuamente comprobando el archivo, y cada vez que aparezca una nueva línea en él la mostrará

Por ejemplo, si yo monitoreo el log de inicio de sesión en mi máquina

	
< > Input
Python
!tail -f /var/log/auth.log
Copied
>_ Output
			
Dec 1 16:27:22 wallabot gcr-prompter[1457]: Gcr: calling the PromptDone method on /org/gnome/keyring/Prompt/p2@:1.26, and ignoring reply
Dec 1 16:27:22 wallabot gnome-keyring-daemon[1178]: asked to register item /org/freedesktop/secrets/collection/login/10, but it's already registered
Dec 1 16:27:26 wallabot systemd-logind[835]: Watching system buttons on /dev/input/event28 (Logitech Wireless Mouse MX Master 3)
Dec 1 16:27:33 wallabot gcr-prompter[1457]: Gcr: 10 second inactivity timeout, quitting
Dec 1 16:27:33 wallabot gcr-prompter[1457]: Gcr: unregistering prompter
Dec 1 16:27:33 wallabot gcr-prompter[1457]: Gcr: disposing prompter
Dec 1 16:27:33 wallabot gcr-prompter[1457]: Gcr: finalizing prompter
Dec 1 16:27:34 wallabot polkitd(authority=local): Operator of unix-session:1 successfully authenticated as unix-user:wallabot to gain TEMPORARY authorization for action org.debian.apt.install-or-remove-packages for system-bus-name::1.96 [/usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map] (owned by unix-user:wallabot)
Dec 1 16:27:42 wallabot systemd-logind[835]: Watching system buttons on /dev/input/event30 (T9-R (AVRCP))
Dec 1 16:27:49 wallabot gnome-keyring-daemon[1178]: asked to register item /org/freedesktop/secrets/collection/login/2, but it's already registered

Vemos en las dos últimas líneas mi inicio de sesión cuando he encendido hoy mi ordenador.

Ahora me conecto por SSH a mi propia máquina

	
< > Input
Python
!ssh localhost
Copied
>_ Output
			
wallabot@localhost's password:
Welcome to Ubuntu 20.04.5 LTS (GNU/Linux 5.15.0-53-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
1 device has a firmware upgrade available.
Run `fwupdmgr get-upgrades` for more information.
Se pueden aplicar 0 actualizaciones de forma inmediata.
Your Hardware Enablement Stack (HWE) is supported until April 2025.
*** System restart required ***
Last login: Sun May 8 02:18:09 2022 from 192.168.1.147

En la consola donde estaba monitorizando el inicio de sesión han aparecido dos nuevas líneas

>_ Output
			
Dec 1 16:32:23 wallabot sshd[25647]: Accepted password for wallabot from 127.0.0.1 port 54668 ssh2
Dec 1 16:32:23 wallabot sshd[25647]: pam_unix(sshd:session): session opened for user wallabot by (uid=0)
Dec 1 16:32:23 wallabot systemd-logind[835]: New session 4 of user wallabot.

Y cuando cierro la sesión SSH aparecen otras dos líneas nuevas

>_ Output
			
Dec 1 16:33:52 wallabot sshd[25647]: pam_unix(sshd:session): session closed for user wallabot
Dec 1 16:33:52 wallabot systemd-logind[835]: Session 4 logged out. Waiting for processes to exit.
Dec 1 16:33:52 wallabot systemd-logind[835]: Removed session 4.

El visor de archivos más potente: lesslink image 20

Uno de los comandos más potentes para ver dentro de los archivos es less

	
< > Input
Python
terminal("less 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)
Copied
>_ Output
			
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "dsaKCKL0IxZl"
},
"source": [
"# Introducción a Python"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ho_8zgIiI0We"
},
"source": [
"## 1. Resumen"
]
},
...
},
"nbformat": 4,
"nbformat_minor": 0
}

Al estar dentro de un cuaderno no se puede ver lo que ocurre realmente al usar less, pero cuando lo usamos nos metemos en el documento, podemos movernos a través de él mediante las teclas o con el ratón

Si queremos buscar algo dentro del documento, escribimos el carácter / y lo que queramos buscar. Para cambiar entre las distintas instancias que ha encontrado pulsamos la tecla n, y si queremos volver hacia atrás en las búsquedas pulsamos shift+n

Para salir solo hay que pulsar q

El visor catlink image 21

No te permite navegar por el archivo ni hacer búsquedas.

	
< > Input
Python
terminal("cat 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)
Copied
>_ Output
			
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "dsaKCKL0IxZl"
},
"source": [
"# Introducción a Python"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ho_8zgIiI0We"
},
"source": [
"## 1. Resumen"
]
},
...
},
"nbformat": 4,
"nbformat_minor": 0
}

Editor por defecto del sistema xdg-openlink image 22

Si lo queremos abrir con el editor por defecto del archivo, tenemos que usar xdg-open

	
< > Input
Python
terminal("xdg-open 2021-02-11-Introducción-a-Python.ipynb")
Copied
>_ Output
			

Si lo que queremos es abrir la carpeta en la que estamos, usamos nautilus

	
< > Input
Python
terminal("nautilus")
Copied
>_ Output
			

Y si lo que queremos es que se abra en una ruta determinada, se incluye la ruta

	
< > Input
Python
terminal("nautilus ~/")
Copied
>_ Output
			

Contador de palabras de un archivo con wc (word count)link image 24

Por último, un comando muy útil es wc (word count), que te muestra cuántas líneas, palabras y bytes tiene un archivo

	
< > Input
Python
terminal("wc 2021-02-11-Introduccion-a-Python.ipynb")
Copied
>_ Output
			
11678 25703 285898 2021-02-11-Introduccion-a-Python.ipynb

Como vemos, el archivo tiene 11678 líneas, 25703 palabras y ocupa 285898 bytes

¿Qué es un comando?link image 25

Un comando puede ser cuatro cosas

  • Un programa ejecutable, estos normalmente se guardan en la ruta /usr/bin
  • Un comando de shell
  • Una función de shell
  • Un alias

Para ver a qué clase pertenece un comando usamos type

	
< > Input
Python
!type cd
Copied
>_ Output
			
cd is a shell builtin
	
< > Input
Python
!type mkdir
Copied
>_ Output
			
mkdir is /usr/bin/mkdir
	
< > Input
Python
!type ls
Copied
>_ Output
			
ls is /usr/bin/ls

¿Qué es un alias?link image 26

Un alias es un comando que definimos nosotros, este se define mediante el comando alias. Por ejemplo, vamos a crear el alias l que lo que haga sea ls -h

	
< > Input
Python
!alias l='ls -l'
Copied

Cuando ejecutamos l nos muestra el resultado de ls -h

	
< > Input
Python
!l
Copied
>_ Output
			
2021-02-11-Introducción-a-Python.ipynb

Pero esto tiene el problema de que cuando cerremos la terminal desaparece el alias. Más adelante aprenderemos a crear alias permanentes

Ayuda de los comandoslink image 27

Ayuda con helplink image 28

Con muchos comandos de la shell, podemos obtener su ayuda mediante el comando help

	
< > Input
Python
!help cd
Copied
>_ Output
			
cd: cd [-L|[-P [-e]]] [dir]
Modifica el directorio de trabajo del shell.
Modifica el directorio actual a DIR. DIR por defecto es el valor de la
variable de shell HOME.
La variable CDPATH define la ruta de búsqueda para el directorio que
contiene DIR. Los nombres alternativos de directorio en CDPATH se
separan con dos puntos (:). Un nombre de directorio nulo es igual que
el directorio actual. Si DIR comienza con una barra inclinada (/),
entonces no se usa CDPATH.
Si no se encuentra el directorio, y la opción del shell "cdable_vars"
está activa, entonces se trata la palabra como un nombre de variable.
Si esa variable tiene un valor, se utiliza su valor para DIR.
Opciones:
-L fuerza a seguir los enlaces simbólicos: resuelve los enlaces
simbólicos en DIR después de procesar las instancias de ".."
-P usa la estructura física de directorios sin seguir los enlaces
simbólicos: resuelve los enlaces simbólicos en DIR antes de procesar
las instancias de ".."
-e si se da la opción -P y el directorio actual de trabajo no se
puede determinar con éxito, termina con un estado diferente de cero.
La acción por defecto es seguir los enlaces simbólicos, como si se
especificara "-L".
".." se procesa quitando la componente del nombre de la ruta inmediatamente
anterior hasta una barra inclinada o el comienzo de DIR.
Estado de Salida:
Devuelve 0 si se cambia el directorio, y si $PWD está definido como
correcto cuando se emplee -P; de otra forma es diferente a cero.

Manual con manlink image 29

Otro comando es man, que hace referencia al manual de usuario.

	
< > Input
Python
terminal("man ls", max_lines_output=20)
Copied
>_ Output
			
LS(1) User Commands LS(1)
NAME
ls - list directory contents
SYNOPSIS
ls [OPTION]... [FILE]...
DESCRIPTION
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is speci‐
fied.
Mandatory arguments to long options are mandatory for short options
too.
-a, --all
do not ignore entries starting with .
-A, --almost-all
...
Full documentation at: &lt;https://www.gnu.org/software/coreutils/ls&gt;
or available locally via: info '(coreutils) ls invocation'
GNU coreutils 8.30 September 2019 LS(1)

Para salir, pulsar q, ya que man utiliza less como visualizador del manual

Información con infolink image 30

Otro comando es info

	
< > Input
Python
terminal("info ls", max_lines_output=20)
Copied
>_ Output
			
File: coreutils.info, Node: ls invocation, Next: dir invocation, Up: Directory listing
10.1 ‘ls’: List directory contents
==================================
The ‘ls’ program lists information about files (of any type, including
directories). Options and file arguments can be intermixed arbitrarily,
as usual.
For non-option command-line arguments that are directories, by
default ‘ls’ lists the contents of directories, not recursively, and
omitting files with names beginning with ‘.’. For other non-option
arguments, by default ‘ls’ lists just the file name. If no non-option
argument is specified, ‘ls’ operates on the current directory, acting as
if it had been invoked with a single argument of ‘.’.
By default, the output is sorted alphabetically, according to the
locale settings in effect.(1) If standard output is a terminal, the
output is in columns (sorted vertically) and control characters are
output as question marks; otherwise, the output is listed one per line
...
‘--show-control-chars’
Print nongraphic characters as-is in file names. This is the
default unless the output is a terminal and the program is ‘ls’.

Para salir, pulsar q, ya que info utiliza less como visualizador de la información

Información de un comando con whatislink image 31

Otro comando es whatis

	
< > Input
Python
terminal("whatis ls")
Copied
>_ Output
			
ls (1) - list directory contents

Wildcardslink image 32

Las wildcards son caracteres especiales que nos sirven para realizar búsquedas especiales. Por ejemplo, si quiero buscar todos los archivos que terminen en .txt. Vamos a crear unos cuantos archivos para verlas.

	
< > Input
Python
terminal("touch file.txt dot.txt dot2.txt index.html datos1 datos123 Abc")
Copied
>_ Output
			
	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
Abc
datos1
datos123
dot2.txt
dot.txt
file.txt
index.html

Todos los caracteres *link image 33

Vamos a buscar ahora todos los archivos .txt

	
< > Input
Python
!ls *.txt
Copied
>_ Output
			
dot2.txt dot.txt file.txt

Vamos ahora a buscar todos los que empiecen por la palabra datos

	
< > Input
Python
!ls datos*
Copied
>_ Output
			
datos1 datos123

Números ?link image 34

Pero qué pasa si en realidad lo que queremos es que nos muestre todos los archivos que empiecen por la palabra datos pero seguidos solo de un número, tenemos que poner un signo de interrogación ?

	
< > Input
Python
!ls datos?
Copied
>_ Output
			
datos1

Si lo que queremos es que tenga tres números, entonces tenemos que poner tres signos de interrogación ???

	
< > Input
Python
!ls datos???
Copied
>_ Output
			
datos123

Mayúsculas [[:upper:]]link image 35

Si queremos que busque los archivos que empiecen por mayúsculas

	
< > Input
Python
!ls [[:upper:]]*
Copied
>_ Output
			
Abc

Minúsculas [[:lower:]]link image 36

Para los archivos que empiecen con minúsculas.

	
< > Input
Python
!ls [[:lower:]]*
Copied
>_ Output
			
datos1 datos123 dot2.txt dot.txt file.txt index.html

Claseslink image 37

Mediante el uso de corchetes podemos crear clases, así si queremos buscar los archivos que empiecen por las letras d o f seguidas de cualquier carácter

	
< > Input
Python
!ls [df]*
Copied
>_ Output
			
datos1 datos123 dot2.txt dot.txt file.txt

Redirecciones: cómo funciona la shelllink image 38

Un comando funciona de la siguiente manera

pipeline comando

Tiene un standard input, que por defecto es el texto que introducimos por teclado, un standard output, que por defecto es el texto que sale por consola y un standard error que también es, por defecto, un texto que sale por consola, pero que tiene otro formato

Redirección del standard outputlink image 39

Pero con el carácter > podemos modificar el standard output de un comando. Por ejemplo, si queremos listar con ls los archivos de la carpeta en la que estamos, pero no queremos que el resultado se imprima por pantalla, sino que se guarde en un archivo, haríamos lo siguiente ls > lista.txt, esto escribe la lista en lista.txt. Además, si lista.txt no existe, lo crea

	
< > Input
Python
!ls &gt; lista.txt
Copied

Vemos que ha creado el archivo y vemos qué hay dentro

	
< > Input
Python
terminal("ls")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
Abc
datos1
datos123
dot2.txt
dot.txt
file.txt
index.html
lista.txt
	
< > Input
Python
terminal("cat lista.txt")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
Abc
datos1
datos123
dot2.txt
dot.txt
file.txt
index.html
lista.txt

Vemos que dentro de lista.txt aparece lista.txt, eso es porque primero crea el archivo y luego ejecuta el comando

Hacemos lo mismo, pero con la carpeta padre

	
< > Input
Python
!ls ../ &gt; lista.txt
Copied

Si volvemos a ver dentro de lista.txt

	
< > Input
Python
terminal("cat lista.txt")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
prueba
__pycache__
ssh.ipynb
test.html
test.ipynb

Vemos que se sobreescribe el contenido

Si lo que queremos es que se concatene el contenido, debemos usar >>

	
< > Input
Python
!ls &gt; lista.txt
Copied
	
< > Input
Python
!ls ../ &gt;&gt; lista.txt
Copied
	
< > Input
Python
terminal("cat lista.txt")
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb
Abc
datos1
datos123
dot2.txt
dot.txt
file.txt
index.html
lista.txt
2021-02-11-Introduccion-a-Python.ipynb
2021-04-23-Calculo-matricial-con-Numpy.ipynb
2021-06-15-Manejo-de-datos-con-Pandas.ipynb
2022-09-12 Introduccion a la terminal.ipynb
2022-09-12 Introduccion a la terminal.txt
command-line-cheat-sheet.pdf
CSS.ipynb
Docker.html
Docker.ipynb
Expresiones regulares.html
Expresiones regulares.ipynb
html_files
html.ipynb
introduccion_python
movies.csv
movies.dat
notebooks_translated
prueba
__pycache__
ssh.ipynb
test.html
test.ipynb

Ahora sí se ha concatenado la información

Esto es muy útil para crear archivos de logs

Redirección del standard errorlink image 40

Si realizamos una operación incorrecta obtenemos un error, veamos qué pasa al redirigir un comando que da un error

	
< > Input
Python
!ls fjhdsalkfs &gt; lista.txt
Copied
>_ Output
			
ls: no se puede acceder a 'fjhdsalkfs': No existe el archivo o el directorio

Como vemos, ha dado un error, pero si ahora vemos dentro de lista.txt

	
< > Input
Python
terminal("cat lista.txt")
Copied
>_ Output
			

Vemos que el archivo está vacío, eso es porque no hemos redireccionado el standard error a lista.txt, sino el standard output. Como hemos visto en la imagen, hay dos estándares de salida en un comando, el primero es el standard output y el segundo el standard error, por lo que para redireccionar el standard error hay que indicarlo mediante 2>. Vamos ahora así

	
< > Input
Python
!ls kjhsfskjd 2&gt; lista.txt
Copied
	
< > Input
Python
terminal("cat lista.txt")
Copied
>_ Output
			
ls: no se puede acceder a 'kjhsfskjd': No existe el archivo o el directorio

Como vemos, ahora sí se ha redirigido

Redirección del standard output y del standard errorlink image 41

Si queremos redirigirlos dos, usamos lo siguiente

	
< > Input
Python
!ls kjhsfskjd &gt; lista.txt 2&gt;&amp;1
Copied

Veamos dentro de lista.txt

	
< > Input
Python
terminal("cat lista.txt")
Copied
>_ Output
			
ls: no se puede acceder a 'kjhsfskjd': No existe el archivo o el directorio

Si ahora ejecutamos un comando sin errores

	
< > Input
Python
!ls . &gt;&gt; lista.txt 2&gt;&amp;1
Copied

Veamos dentro de lista.txt (**ojo**, ahora hemos concatenado)

	
< > Input
Python
terminal("cat lista.txt")
Copied
>_ Output
			
ls: no se puede acceder a 'kjhsfskjd': No existe el archivo o el directorio
2021-02-11-Introduccion-a-Python.ipynb
Abc
datos1
datos123
dot2.txt
dot.txt
file.txt
index.html
lista.txt

Cómo se puede ver, se han redirigido, tanto el standard error, como el standard output al mismo archivo

Pipelineslink image 42

Podemos crear pipelines haciendo que el standard output de un comando se convierta en el standard input de otro. Por ejemplo, vamos a hacer que la salida de ls -lha sea la entrada de grep, que lo veremos más adelante, pero es un comando para buscar.

	
< > Input
Python
!ls -lha | grep -i "txt"
Copied
>_ Output
			
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt

Como podemos ver, lo que hemos hecho ha sido llevar la salida de ls a grep con el cual hemos buscado algún archivo con txt en el nombre

Operadores de control - encadenar comandoslink image 43

Comandos de manera secuenciallink image 44

Una forma de encadenar comandos de forma secuencial es separarlos mediante ;. Esto crea diferentes hilos para cada tarea

	
< > Input
Python
!ls; echo 'Hola'; cal
Copied
>_ Output
			
2021-02-11-Introduccion-a-Python.ipynb datos123 file.txt
Abc dot2.txt index.html
datos1 dot.txt lista.txt
Hola
Diciembre 2022
do lu ma mi ju vi sá
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Como podemos ver, primero se ha ejecutado el comando ls, luego se ha impreso Hola gracias al comando echo "Hola" y por último se ha impreso un calendario gracias al comando cal

Vamos ahora a hacer otro ejemplo para ver que se ejecutan de manera secuencial.

	
< > Input
Python
!echo "Before touch;"; ls -lha; touch secuential.txt; echo "After touch:"; ls -lha
Copied
>_ Output
			
Before touch;
total 292K
drwxrwxr-x 2 wallabot wallabot 4,0K dic 6 01:04 .
drwxrwxr-x 7 wallabot wallabot 4,0K dic 6 00:24 ..
-rw-rw-r-- 1 wallabot wallabot 280K dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
After touch:
total 292K
drwxrwxr-x 2 wallabot wallabot 4,0K dic 6 01:07 .
drwxrwxr-x 7 wallabot wallabot 4,0K dic 6 00:24 ..
-rw-rw-r-- 1 wallabot wallabot 280K dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 01:07 secuential.txt

Como se puede ver, en el primer ls no aparece sequential.txt, mientras que en el segundo sí. Eso quiere decir que los comandos se han ejecutado en orden, uno detrás de otro

Comandos de manera paralelalink image 45

Si lo que queremos es que los comandos se ejecuten de manera paralela, hay que usar el operador &. Esto hará que se cree un nuevo proceso por cada comando.

Veamos el ejemplo de antes

	
< > Input
Python
!rm secuential.txt
Copied
	
< > Input
Python
!echo "Before touch;" &amp; ls -lha &amp; touch secuential.txt &amp; echo "After touch:" &amp; ls -lha
Copied
>_ Output
			
Before touch;
After touch:
total 292K
drwxrwxr-x 2 wallabot wallabot 4,0K dic 6 01:08 .
drwxrwxr-x 7 wallabot wallabot 4,0K dic 6 00:24 ..
-rw-rw-r-- 1 wallabot wallabot 280K dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 01:08 secuential.txt

Ahora se puede ver que no se han ejecutado secuencialmente, ya que primero se han ejecutado los echos, que serán los que menos tarden, y después el resto

Comandos de manera condicionallink image 46

Andlink image 47

Utilizando el operador &&, un comando se ejecutará cuando el anterior se haya ejecutado satisfactoriamente

	
< > Input
Python
!rm secuential.txt
Copied
	
< > Input
Python
!echo "Before touch;" && ls -lha && touch secuential.txt && echo "After touch:" && ls -lha
Copied
>_ Output
			
Before touch;
total 292K
drwxrwxr-x 2 wallabot wallabot 4,0K dic 6 01:08 .
drwxrwxr-x 7 wallabot wallabot 4,0K dic 6 00:24 ..
-rw-rw-r-- 1 wallabot wallabot 280K dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
After touch:
total 292K
drwxrwxr-x 2 wallabot wallabot 4,0K dic 6 01:08 .
drwxrwxr-x 7 wallabot wallabot 4,0K dic 6 00:24 ..
-rw-rw-r-- 1 wallabot wallabot 280K dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 01:08 secuential.txt

Aquí podemos ver cómo se ha ejecutado uno detrás de otro, es decir, un comando no empieza hasta que el anterior acaba

Pero entonces, ¿cuál es la diferencia entre ; y &&?

En el primero, el secuencial ;, primero se ejecuta un comando y luego otro, pero para que se ejecute un comando da igual que el anterior se haya ejecutado satisfactoriamente

	
< > Input
Python
!rm prueba ; ls -lha
Copied
>_ Output
			
rm: no se puede borrar 'prueba': No existe el archivo o el directorio
total 292K
drwxrwxr-x 2 wallabot wallabot 4,0K dic 6 01:08 .
drwxrwxr-x 7 wallabot wallabot 4,0K dic 6 00:24 ..
-rw-rw-r-- 1 wallabot wallabot 280K dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 01:08 secuential.txt

Como se puede ver, primero se ejecuta rm prueba, da un error y aun así se ejecuta ls -lha prueba

En la forma condicional &&, si un comando no se ejecuta satisfactoriamente, el siguiente no se ejecuta.

	
< > Input
Python
!rm prueba && ls -lha
Copied
>_ Output
			
rm: no se puede borrar 'prueba': No existe el archivo o el directorio

Cómo se puede ver ls -lha prueba no se ejecuta ya que rm prueba ha dado un error

Orlink image 48

A diferencia del &&, el 'or' ejecutará todos los procesos, sea cual sea su resultado. Se ha de utilizar el operador ||

	
< > Input
Python
!rm prueba || ls -lha
Copied
>_ Output
			
rm: no se puede borrar 'prueba': No existe el archivo o el directorio
total 292K
drwxrwxr-x 2 wallabot wallabot 4,0K dic 6 01:08 .
drwxrwxr-x 7 wallabot wallabot 4,0K dic 6 00:24 ..
-rw-rw-r-- 1 wallabot wallabot 280K dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 01:08 secuential.txt

La diferencia entre este y ; es que el || (or) no crea un nuevo hilo para cada comando

Cómo se manejan los permisoslink image 49

Cuando se listan los archivos de un directorio con el flag -l (long) aparecen unos símbolos al lado de cada archivo.

	
< > Input
Python
!mkdir subdirectorio
Copied
	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 288
-rw-rw-r-- 1 wallabot wallabot 285898 dic 6 00:28 2021-02-11-Introduccion-a-Python.ipynb
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 Abc
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos1
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 datos123
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot2.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 dot.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 file.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 00:56 index.html
-rw-rw-r-- 1 wallabot wallabot 182 dic 6 01:06 lista.txt
-rw-rw-r-- 1 wallabot wallabot 0 dic 6 01:08 secuential.txt
drwxrwxr-x 2 wallabot wallabot 4096 dic 6 01:10 subdirectorio

Esto nos da información de cada archivo

Primero veamos qué tipos de archivos hay

  • -: Archivo normal
  • d: Directorio
  • l: Enlace simbólico* b: Archivo de bloque especial. Son archivos que manejan la información de los bloques de datos como, por ejemplo, un USB

Después veremos los tipos de modo:

Dueño Grupo World
rwx r-x r-x
1 1 1 1 0 1 1 0 1
7 5 5
  • r: read
  • w: write
  • x: execute

Modo simbólico:

  • u: Solo para el usuario
  • g: Sólo para el grupo
  • o: Solo para otros (world) * a: Para todos

Modificando los permisos en la terminallink image 50

Creamos un nuevo archivo

	
< > Input
Python
terminal("cd subdirectorio")
Copied
	
< > Input
Python
!echo "hola mundo" &gt; mitexto.txt
Copied
	
< > Input
Python
!cat mitexto.txt
Copied
>_ Output
			
hola mundo

Vamos a ver los permisos que tiene.

	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 4
-rw-rw-r-- 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt

Como vemos, tiene permisos de lectura y escritura para mi usuario y el grupo, y solo permisos de lectura para el resto (world)

Cambio de permisos con chmod (change mode)link image 51

Para cambiar los permisos de un archivo usamos el comando chmod (change mode), donde tenemos que poner en octal los permisos del usuario, luego los del grupo y por último los del resto.

	
< > Input
Python
!chmod 755 mitexto.txt
Copied
	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 4
-rwxr-xr-x 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt

Vemos que ahora mi usuario tiene permisos de lectura, escritura y ejecución, mientras que el grupo y el resto del mundo tienen permisos de lectura y ejecución

Vamos a quitar los permisos de lectura solo a mi usuario. Para cambiar solo los permisos de un usuario usamos el identificador simbólico, un + si queremos agregar permisos o un - si queremos quitarlos o un = si queremos restablecerlos y seguido del tipo de permiso

	
< > Input
Python
!chmod u-r mitexto.txt
Copied
	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 4
--wxr-xr-x 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
	
< > Input
Python
!cat mitexto.txt
Copied
>_ Output
			
cat: mitexto.txt: Permiso denegado

Como vemos, al quitar permisos de lectura para mi usuario, no podemos leer el archivo.

Le volvemos a poner el permiso de lectura

	
< > Input
Python
!chmod u+r mitexto.txt
Copied
	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 4
-rwxr-xr-x 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
	
< > Input
Python
!cat mitexto.txt
Copied
>_ Output
			
hola mundo

Si queremos agregar o quitar permisos a más de un usuario, lo hacemos separando cada permiso por una ,

	
< > Input
Python
!chmod u-x,go=w mitexto.txt
Copied
	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 4
-rw--w--w- 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt

Como se puede ver, se le ha quitado el permiso de ejecución al usuario y se ha establecido el permiso de solo escritura para el grupo y el resto del mundo.

Identificación de usuario con whoamilink image 52

Para saber quiénes somos podemos usar el comando whoami (who am I)

	
< > Input
Python
!whoami
Copied
>_ Output
			
wallabot

Información de usuario con idlink image 53

Otra manera, que además da más información, es el comando id

	
< > Input
Python
!id
Copied
>_ Output
			
uid=1000(wallabot) gid=1000(wallabot) grupos=1000(wallabot),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),120(lpadmin),131(lxd),132(sambashare),998(docker)

Este comando nos dice que nuestro ID de usuario es el 1000, el ID de grupo es el 1000 y que pertenecemos a los grupos wallabot, adm, cdrom, sudo, dip, plugdev, lpadmin, lxd, sambashare y docker

Cambio de usuario con el comando su (switch user)link image 54

Si queremos cambiar de usuario usamos el comando su (switch user). Para según qué usuario hay que usar sudo (superuser do)

	
< > Input
Python
!sudo su root
Copied
>_ Output
			
root@wallabot:/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio#

Como vemos, cambia el prompt y ahora indica que somos el usuario root

Vamos a la carpeta home

	
< > Input
Python
!cd
Copied
>_ Output
			
root@wallabot:~#

Pero en Linux hay una carpeta home por cada usuario, esto lo podemos ver si ejecutamos el comando pwd

	
< > Input
Python
!pwd
Copied
>_ Output
			
/root

Voy a crear un archivo en la carpeta donde antes he creado el archivo *mitexto.txt*

	
< > Input
Python
!touch /home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio/rootfile.txt
Copied
>_ Output
			

Vuelvo a cambiarme a mi usuario

	
< > Input
Python
!su wallabot
Copied
>_ Output
			
wallabot@wallabot:

Y me voy al directorio donde están los archivos que he creado.

	
< > Input
Python
!cd /home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio
Copied

Vemos los archivos que hay y sus permisos

	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 4
-rw--w--w- 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
-rw-r--r-- 1 root root 0 dic 6 01:22 rootfile.txt

Como vemos, el usuario y el grupo del archivo *rootfile.txt* son el usuario root

Sí, ahora que soy el usuario *wallabot*, intento borrar el archivo rootfile.txt

	
< > Input
Python
!rm rootfile.txt
Copied
>_ Output
			
rm: ¿borrar el fichero regular vacío 'rootfile.txt' protegido contra escritura? (s/n)

Como vemos, nos pregunta si lo queremos borrar, ya que pertenece a otro usuario.

Modificar la contraseña de un usuariolink image 55

Si quiero modificar la contraseña del usuario que tengo actualmente activo, uso el comando passwd (password)

Primero compruebo qué usuario soy

	
< > Input
Python
!whoami
Copied
>_ Output
			
wallabot

Y ahora probamos a cambiar la contraseña

	
< > Input
Python
!passwd
Copied
>_ Output
			
$ passwd
Cambiando la contraseña de wallabot.
Contraseña actual de :
Nueva contraseña:
Vuelva a escribir la nueva contraseña

Como vemos, pide la actual contraseña para poder cambiarla

Podemos crear enlaces simbólicos a una ruta determinada mediante el comando ln (link) seguido del flag -s (symbolic), el directorio y el nombre del enlace

	
< > Input
Python
!ln -s /home/wallabot/Documentos/web web
Copied

Si ahora listamos los archivos

	
< > Input
Python
!ls -l
Copied
>_ Output
			
total 4
-rw--w--w- 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
-rw-r--r-- 1 root root 0 dic 6 01:22 rootfile.txt
lrwxrwxrwx 1 wallabot wallabot 29 dic 6 01:28 web -&gt; /home/wallabot/Documentos/web

Vemos el enlace simbólico web que apunta a /home/wallabot/Documentos/web:

Yo ahora me puedo ir a web

	
< > Input
Python
terminal("cd web")
Copied
	
< > Input
Python
!pwd
Copied
>_ Output
			
/home/wallabot/Documentos/web

Configurar las variables de entornolink image 57

Ver las variables de entorno con printenvlink image 58

Con el comando printenv podemos ver todas las variables de entorno

	
< > Input
Python
!printenv
Copied
>_ Output
			
GJS_DEBUG_TOPICS=JS ERROR;JS LOG
VSCODE_CWD=/home/wallabot
LESSOPEN=| /usr/bin/lesspipe %s
CONDA_PROMPT_MODIFIER=(base)
PYTHONIOENCODING=utf-8
USER=wallabot
VSCODE_NLS_CONFIG={"locale":"es","availableLanguages":{"*":"es"},"_languagePackId":"b07c40c9acb9e1d7b3ca14b06f814803.es","_translationsConfigFile":"/home/wallabot/.config/Code/clp/b07c40c9acb9e1d7b3ca14b06f814803.es/tcf.json","_cacheRoot":"/home/wallabot/.config/Code/clp/b07c40c9acb9e1d7b3ca14b06f814803.es","_resolvedLanguagePackCoreLocation":"/home/wallabot/.config/Code/clp/b07c40c9acb9e1d7b3ca14b06f814803.es/6261075646f055b99068d3688932416f2346dd3b","_corruptedFile":"/home/wallabot/.config/Code/clp/b07c40c9acb9e1d7b3ca14b06f814803.es/corrupted.info","_languagePackSupport":true}
VSCODE_HANDLES_UNCAUGHT_ERRORS=true
MPLBACKEND=module://ipykernel.pylab.backend_inline
SSH_AGENT_PID=1373
XDG_SESSION_TYPE=x11
SHLVL=0
HOME=/home/wallabot
CHROME_DESKTOP=code-url-handler.desktop
CONDA_SHLVL=1
DESKTOP_SESSION=ubuntu
GIO_LAUNCHED_DESKTOP_FILE=/usr/share/applications/code.desktop
VSCODE_IPC_HOOK=/run/user/1000/vscode-26527400-1.73.1-main.sock
PYTHONUNBUFFERED=1
GTK_MODULES=gail:atk-bridge
...
QT_IM_MODULE=ibus
GIT_PAGER=cat
PWD=/home/wallabot/Documentos/web
CLICOLOR=1
XDG_DATA_DIRS=/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop
XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdg
VSCODE_CODE_CACHE_PATH=/home/wallabot/.config/Code/CachedData/6261075646f055b99068d3688932416f2346dd3b
CONDA_EXE=/home/wallabot/anaconda3/bin/conda
CONDA_PREFIX=/home/wallabot/anaconda3
VSCODE_PID=3897

Ver una variable de entorno con el comando echolink image 59

Para ver una variable de entorno en concreto podemos hacerlo mediante el comando echo seguido del símbolo $ y el nombre de la variable

	
< > Input
Python
!echo $HOME
Copied
>_ Output
			
/home/wallabot

Modificar una variable de entorno para una sesión de terminallink image 60

Podemos modificar una variable de entorno para la sesión activa de terminal, por ejemplo, vamos a agregar una nueva ruta a la variable PATH. Primero vemos qué hay en ella

	
< > Input
Python
!echo $PATH
Copied
>_ Output
			
/home/wallabot/anaconda3/bin:/home/wallabot/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

Ahora añadimos un nuevo directorio

	
< > Input
Python
!PATH=$PATH:"subdirectorio
Copied
>_ Output
			

Volvemos a ver qué hay dentro de PATH

	
< > Input
Python
!echo $PATH
Copied
>_ Output
			
/home/wallabot/anaconda3/bin:/home/wallabot/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:subdirectorio

Vemos que se ha añadido el directorio subdirectorio.

El problema de este método es que cuando abramos una nueva terminal no se mantendrá este cambio en PATH

Modificar una variable de entorno para todas las sesiones de terminallink image 61

Nos vamos a la carpeta home

	
< > Input
Python
terminal("cd /home/wallabot")
Copied

Aquí, en el home, listamos todos los archivos con el flag -a (all)

	
< > Input
Python
!ls -a
Copied
>_ Output
			
. .eclipse .pki
.. Escritorio Plantillas
.afirma .gitconfig .platformio
anaconda3 .gnupg .profile
.audacity-data Imágenes .psensor
.bash_history .ipython Público
.bash_logout .java .python_history
.bashrc .jupyter snap
.cache .lesshst .ssh
.conda Lightworks .sudo_as_admin_successful
.config .Lightworks.thereCanBeOnlyOne .thunderbird
.cortex-debug .local Vídeos
.cyberghost logiops .vnc
.dbus .MCTranscodingSDK .vscode
Descargas .mozilla .wget-hsts
.docker Música
Documentos .nv

Vemos que hay un archivo que se llama .bashrc, este archivo es el que tiene la configuración de nuestro bash

	
< > Input
Python
terminal("cat .bashrc", max_lines_output=3)
Copied
>_ Output
			
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
...
fi
unset __conda_setup
# &lt;&lt;&lt; conda initialize &lt;&lt;&lt;

Este archivo es el que configura la terminal cada vez que se abre una nueva, por lo que si en él editamos la variable PATH, este cambio se mantendrá para todas las ventanas nuevas de terminal que abramos

Para modificar la variable PATH dentro del archivo de configuración, tenemos que agregar la siguiente línea al archivo

PATH=$PATH:"subdirectorio"

Crear alias para todas las sesioneslink image 62

Ya vimos cómo crear alias de comandos, pero también pasaba que se perdían cada vez que cerrábamos una sesión de terminal. Para que esto no pase, los añadimos también al archivo de configuración .bashrc. Por ejemplo, en mi caso he añadido las siguientes líneas

alias ll='ls -l'
alias la='ls -a'
alias lh='ls -h'
alias lha='ls -lha'

Comandos de búsquedalink image 63

Búsqueda de binarios con whichlink image 64

El primer comando de búsqueda que vamos a ver es which que nos permite encontrar la ruta de los binarios

	
< > Input
Python
!which python
Copied
>_ Output
			
/home/wallabot/anaconda3/bin/python

Sin embargo, si buscamos algo que no esté en alguna de las rutas del PATH, which no será capaz de decirnos la ruta

	
< > Input
Python
!which cd
Copied

Búsqueda de archivos con findlink image 65

Para buscar un archivo con find tenemos que indicarle desde qué ruta queremos buscar el archivo, seguido del flag -name y el nombre del archivo que queremos buscar.

	
< > Input
Python
!find ~ -name "2021-02-11-Introduccion-a-Python.ipynb"
Copied
>_ Output
			
/home/wallabot/Documentos/web/portafolio/posts/prueba/2021-02-11-Introduccion-a-Python.ipynb
/home/wallabot/Documentos/web/portafolio/posts/2021-02-11-Introduccion-a-Python.ipynb

Como vemos, está en su directorio, más la copia que he creado en este notebook y la he guardado en la carpeta prueba

Una cosa muy poderosa de find es que podemos usar wildcards, por ejemplo, si quiero buscar todos los archivos de texto de mi carpeta web.

	
< > Input
Python
!find ~/Documentos/web/ -name *.txt
Copied
>_ Output
			
/home/wallabot/Documentos/web/portafolio/posts/2022-09-12 Introduccion a la terminal.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/lista.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/dot.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/dot2.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/secuential.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio/rootfile.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio/mitexto.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/file.txt
/home/wallabot/Documentos/web/wordpress_api_rest/page.txt

Si no queremos que distinga entre mayúsculas y minúsculas, debemos usar el flag -iname. Por ejemplo, si buscamos todos los archivos que contengan el texto FILE, pero usando el flag -iname.

	
< > Input
Python
!find ~/Documentos/web/ -iname *FILE*
Copied
>_ Output
			
/home/wallabot/Documentos/web/portafolio/posts/html_files
/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio/rootfile.txt
/home/wallabot/Documentos/web/portafolio/posts/prueba/file.txt

Vemos que todos los resultados contienen file y no FILE, es decir, no ha hecho distinción entre mayúsculas y minúsculas

Podemos especificar el tipo de archivo con el flag -type. Solo admite dos tipos f para archivos y d para directorios

	
< > Input
Python
!find ~/Documentos/nerf -name image*
Copied
>_ Output
			
/home/wallabot/Documentos/nerf/instant-ngp/configs/image
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/benchmarks/image
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/dependencies/cutlass/media/images
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/dependencies/fmt/doc/bootstrap/mixins/image.less
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/data/images
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/dlss/NVIDIAImageScaling/samples/media/images
/home/wallabot/Documentos/nerf/instant-ngp/data/nerf/fox/images
/home/wallabot/Documentos/nerf/instant-ngp/data/image
	
< > Input
Python
!find ~/Documentos/nerf -name image* -type d
Copied
>_ Output
			
/home/wallabot/Documentos/nerf/instant-ngp/configs/image
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/benchmarks/image
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/dependencies/cutlass/media/images
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/data/images
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/dlss/NVIDIAImageScaling/samples/media/images
/home/wallabot/Documentos/nerf/instant-ngp/data/nerf/fox/images
/home/wallabot/Documentos/nerf/instant-ngp/data/image
	
< > Input
Python
!find ~/Documentos/nerf -name image* -type f
Copied
>_ Output
			
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/dependencies/fmt/doc/bootstrap/mixins/image.less

Si queremos filtrar por el tamaño del archivo podemos usar el flag -size, por ejemplo, si queremos buscar todos los archivos de más de 200 MB

	
< > Input
Python
!find ~/Documentos/ -type f -size +200M
Copied
>_ Output
			
/home/wallabot/Documentos/kaggle/hubmap/models/13_efficientnet-b7_final_model.pth
/home/wallabot/Documentos/kaggle/hubmap/models/12_efficientnet-b7_final_model.pth
/home/wallabot/Documentos/kaggle/hubmap/models/14_resnet152_final_model.pth
/home/wallabot/Documentos/kaggle/hubmap/models/14_resnet152_best_model.pth
/home/wallabot/Documentos/kaggle/hubmap/models/12_efficientnet-b7_early_stopping.pth
/home/wallabot/Documentos/kaggle/hubmap/models/efficientnet-b7-dcc49843.pth
/home/wallabot/Documentos/kaggle/hubmap/models/13_efficientnet-b7_early_stopping.pth
/home/wallabot/Documentos/kaggle/hubmap/models/14_resnet152_early_stopping.pth
/home/wallabot/Documentos/kaggle/hubmap/models/12_efficientnet-b7_best_model.pth
/home/wallabot/Documentos/kaggle/hubmap/models/13_efficientnet-b7_best_model.pth

Si queremos realizar operaciones tras la búsqueda, usamos el flag -exec

Por ejemplo, voy a buscar todas las carpetas con el nombre subdirectorio

	
< > Input
Python
!find ~/ -name subdirectorio -type d
Copied
>_ Output
			
/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio

Puedo hacer que se borren con el flag -exec

	
< > Input
Python
!find ~/ -name subdirectorio -type d -exec rm -r {} ;
Copied
>_ Output
			
rm: ¿borrar el fichero regular vacío '/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio/rootfile.txt' protegido contra escritura? (s/n) s
find: ‘/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio’: No existe el archivo o el directorio
	
< > Input
Python
!find ~/ -name subdirectorio -type d
Copied

Por último, si usamos el carácter ! estaremos indicando que encuentre todo lo que no coincide con lo que hemos especificado

	
< > Input
Python
!find ~/Documentos/web/portafolio/posts/prueba ! -name *.txt
Copied
>_ Output
			
/home/wallabot/Documentos/web/portafolio/posts/prueba
/home/wallabot/Documentos/web/portafolio/posts/prueba/index.html
/home/wallabot/Documentos/web/portafolio/posts/prueba/Abc
/home/wallabot/Documentos/web/portafolio/posts/prueba/datos1
/home/wallabot/Documentos/web/portafolio/posts/prueba/2021-02-11-Introduccion-a-Python.ipynb
/home/wallabot/Documentos/web/portafolio/posts/prueba/datos123

Como vemos, ha encontrado todo lo que no es un .txt

Comando de búsqueda greplink image 66

grep es un comando de búsqueda muy potente, por eso le dedicamos un apartado a él solo. El comando grep utiliza las expresiones regulares, por lo que si quieres aprender de ellas te dejo un enlace a un post donde las explico

Vamos a empezar a ver la potencia de este comando, vamos a buscar todas las veces que aparece el texto MáximoFN dentro del archivo 2021-02-11-Introduccion-a-Python.ipynb

	
< > Input
Python
terminal("cd /home/wallabot/Documentos/web/portafolio/posts/prueba")
Copied
	
< > Input
Python
terminal("grep MaximoFN 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)
Copied
>_ Output
			
"a = 'MaximoFN' ",
"'MaximoFN'"
"string = "MaximoFN" ",
"'MaximoFN'"
"string = 'MaximoFN' ",
"'MaximoFN'"
"Este es el blog de "MaximoFN" "
"print("Este es el blog de \"MaximoFN\"")"
"Este es el blog de 'MaximoFN' "
"print('Este es el blog de \'MaximoFN\'')"
"Este es el blog de \MaximoFN\ "
"print('Este es el blog de \\MaximoFN\\')"
"MaximoFN "
"print('Este es el blog de \nMaximoFN')"
"Este es el blog de MaximoFN "
"print('Esto no se imprimirá \rEste es el blog de MaximoFN')"
"Este es el blog de MaximoFN "
"print('Este es el blog de \tMaximoFN')"
"Este es el blog deMaximoFN "
"print('Este es el blog de \bMaximoFN')"
...
"funcion2_del_modulo('MaximoFN')"
"MaximoFN ",
" print('MaximoFN') ",
" variable = 'MaximoFN' ",

Sin embargo, si hacemos la misma búsqueda para el texto maximofn

	
< > Input
Python
!grep maximofn 2021-02-11-Introduccion-a-Python.ipynb
Copied

No aparece ningún resultado, esto es porque grep es case sensitive, es decir, busca el texto tal cual se lo has introducido, diferenciando mayúsculas y minúsculas. Si no queremos esto, tenemos que introducir el flag -i

	
< > Input
Python
terminal("grep -i MaximoFN 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)
Copied
>_ Output
			
"a = 'MaximoFN' ",
"'MaximoFN'"
"string = "MaximoFN" ",
"'MaximoFN'"
"string = 'MaximoFN' ",
"'MaximoFN'"
"Este es el blog de "MaximoFN" "
"print("Este es el blog de \"MaximoFN\"")"
"Este es el blog de 'MaximoFN' "
"print('Este es el blog de \'MaximoFN\'')"
"Este es el blog de \MaximoFN\ "
"print('Este es el blog de \\MaximoFN\\')"
"MaximoFN "
"print('Este es el blog de \nMaximoFN')"
"Este es el blog de MaximoFN "
"print('Esto no se imprimirá \rEste es el blog de MaximoFN')"
"Este es el blog de MaximoFN "
"print('Este es el blog de \tMaximoFN')"
"Este es el blog deMaximoFN "
"print('Este es el blog de \bMaximoFN')"
...
"funcion2_del_modulo('MaximoFN')"
"MaximoFN ",
" print('MaximoFN') ",
" variable = 'MaximoFN' ",

Si lo que queremos es que nos devuelva el número de veces que aparece, introducimos el flag -c

	
< > Input
Python
!grep -c MaximoFN 2021-02-11-Introduccion-a-Python.ipynb
Copied
>_ Output
			
105

Si nos da igual si aparece con mayúscula o minúscula, podemos volver a agregar el flag -i, pero no hace falta meterlo separado del flag -c, se pueden introducir juntos

	
< > Input
Python
!grep -ci MaximoFN 2021-02-11-Introduccion-a-Python.ipynb
Copied
>_ Output
			
105

Si ahora queremos todas las veces en las que **no** aparece la palabra MáximoFN introducimos el flag -v

	
< > Input
Python
!grep -cv MaximoFN 2021-02-11-Introduccion-a-Python.ipynb
Copied
>_ Output
			
11573

---

➡️ **Continúa en la Parte 2: red, compresión y procesos**, donde aprenderás a moverte por la red y a controlar los procesos del sistema.

Seguir leyendo

Últimos posts -->

¿Has visto estos proyectos?

Gymnasia

Gymnasia Gymnasia
React Native
Expo
TypeScript
FastAPI
Next.js
OpenAI
Anthropic

Aplicación móvil de entrenamiento personal con asistente de IA, biblioteca de ejercicios, seguimiento de rutinas, dieta y medidas corporales

Horeca chatbot

Horeca chatbot Horeca chatbot
Python
LangChain
PostgreSQL
PGVector
React
Kubernetes
Docker
GitHub Actions

Chatbot conversacional para cocineros de hoteles y restaurantes. Un cocinero, jefe de cocina o camaeror de un hotel o restaurante puede hablar con el chatbot para obtener información de recetas y menús. Pero además implementa agentes, con los cuales puede editar o crear nuevas recetas o menús

Naviground

Naviground Naviground
Ver todos los proyectos -->
>_ Disponible para proyectos

¿Tienes un proyecto con IA?

Hablemos.

maximofn@gmail.com

Especialista en Machine Learning e Inteligencia Artificial. Desarrollo soluciones con IA generativa, agentes inteligentes y modelos personalizados.

¿Quieres ver alguna charla?

Últimas charlas -->

¿Quieres mejorar con estos tips?

Últimos tips -->

Usa esto en local

Los espacios de Hugging Face nos permite ejecutar modelos con demos muy sencillas, pero ¿qué pasa si la demo se rompe? O si el usuario la elimina? Por ello he creado contenedores docker con algunos espacios interesantes, para poder usarlos de manera local, pase lo que pase. De hecho, es posible que si pinchas en alún botón de ver proyecto te lleve a un espacio que no funciona.

Flow edit

Flow edit Flow edit

Edita imágenes con este modelo de Flow. Basándose en SD3 o FLUX puedes editar cualquier imagen y generar nuevas

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
Ver todos los contenedores -->
>_ Disponible para proyectos

¿Tienes un proyecto con IA?

Hablemos.

maximofn@gmail.com

Especialista en Machine Learning e Inteligencia Artificial. Desarrollo soluciones con IA generativa, agentes inteligentes y modelos personalizados.

¿Quieres entrenar tu modelo con estos datasets?

short-jokes-dataset

HuggingFace

Dataset de chistes en inglés

Uso: Fine-tuning de modelos de generación de texto humorístico

231K filas 2 columnas 45 MB
Ver en HuggingFace →

opus100

HuggingFace

Dataset con traducciones de inglés a español

Uso: Entrenamiento de modelos de traducción inglés-español

1M filas 2 columnas 210 MB
Ver en HuggingFace →

netflix_titles

HuggingFace

Dataset con películas y series de Netflix

Uso: Análisis de catálogo de Netflix y sistemas de recomendación

8.8K filas 12 columnas 3.5 MB
Ver en HuggingFace →
Ver más datasets -->