Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
π **This post is part of the _Introduction to the terminal_ series**, divided into three chapters that should be read in order:
> * π **Part 1: Navigation, files and commands**
* Part 2: Network, compression and processes
* Part 3: System administration
Post format
To avoid having to keep putting console screenshots in every action I take, I have created the following function that receives the terminal command we want to execute and returns the output that the terminal would give us.
Sometimes I will use this function, and other times I will use ! before each command, which in notebooks means you are going to execute a terminal command.
InputPythonimport subprocessimport oslast_directory = ''def terminal(command, max_lines_output=None):global last_directorydebug = Falsestr = command.split()# Check if there are " or ' charactersfor i in range(len(str)):if debug: print(f"i = {i}, str[i] = {str[i]}")if len(str[i]) > 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 stringsstr = [x for x in str if x != ""]if debug:print(str)returnif 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_direlse: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
First commands to move around the terminal
ls (listar directorio)
The first command we are going to see is ls (list directory), which is used to list all the files in the folder we are in.
InputPythonterminal("ls")Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translated__pycache__ssh.ipynbtest.htmltest.ipynb
Commands can normally receive options (flags), which are introduced with the character -, for example, let's look at ls -l, which returns the list of files in the directory we are in, but with more information
InputPythonterminal('ls -l')Copied
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.ipynbdrwxrwxr-x 2 wallabot wallabot 4096 nov 28 14:39 html_files-rw-rw-r-- 1 wallabot wallabot 14775 sep 18 03:29 html.ipynbdrwxrwxr-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.datdrwxrwxr-x 2 wallabot wallabot 4096 nov 28 14:39 notebooks_translateddrwxrwxr-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
As we can see, we have how many bytes each file occupies, but when we have files that take up a lot of space, this is not very easy to read, so we can add the h (human) option, which gives us information that is easier to read
InputPythonterminal('ls -lh')Copied
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.ipynbdrwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 html_files-rw-rw-r-- 1 wallabot wallabot 15K sep 18 03:29 html.ipynbdrwxrwxr-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.datdrwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 notebooks_translateddrwxrwxr-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
If we want to see hidden files, we can use the a option, which will show us all the files in a directory.
InputPythonterminal('ls -lha')Copied
total 4,5Mdrwxrwxr-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.ipynbdrwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 html_files-rw-rw-r-- 1 wallabot wallabot 15K sep 18 03:29 html.ipynbdrwxrwxr-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.datdrwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 notebooks_translateddrwxrwxr-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
If what we want is for it to sort them by size, we can use the S option
InputPythonterminal('ls -lhS')Copied
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.ipynbdrwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 html_filesdrwxrwxr-x 3 wallabot wallabot 4,0K nov 12 01:51 introduccion_pythondrwxrwxr-x 2 wallabot wallabot 4,0K nov 28 14:39 notebooks_translateddrwxrwxr-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
If we want it to show us the files sorted alphabetically, but in reverse, we must use the -r option
InputPythonterminal('ls -lhr')Copied
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.ipynbdrwxrwxr-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.csvdrwxrwxr-x 3 wallabot wallabot 4,0K nov 12 01:51 introduccion_python-rw-rw-r-- 1 wallabot wallabot 15K sep 18 03:29 html.ipynbdrwxrwxr-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)
The second command will be cd (change directory), which allows us to change directories
InputPythonterminal('cd /home/wallabot/Documentos/')Copied
If we now use ls again to see the files we have, we see that they change
InputPythonterminal('ls')Copied
aprendiendo-git.pdfbalena-etcher-electron-1.7.9-linux-x64camerasIPDocumentaciongstreamergstreamer_oldjetsonNanokaggleLibrosnerfprueba.txtpytorchwallabotweb
If to cd, instead of giving it the directory we want to move to, we give it the - character, it will return to the previous directory where it was
InputPythonterminal('cd -')Copied
InputPythonterminal('ls')Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translated__pycache__ssh.ipynbtest.htmltest.ipynb
If we wanted to move to the home directory by entering only cd in the terminal, it would take us there.
InputPythonterminal('cd')Copied
pwd (print working directory)
To get the directory we are in, we can use pwd (print working directory)
InputPythonterminal('pwd')Copied
/home/wallabot
We can move using the cd command via relative paths and absolute paths. For example, letβs move to a directory using an absolute path.
InputPythonterminal('cd /home/wallabot/Documentos/')Copied
InputPythonterminal('pwd')Copied
/home/wallabot/Documentos
InputPythonterminal('ls')Copied
aprendiendo-git.pdfbalena-etcher-electron-1.7.9-linux-x64camerasIPDocumentaciongstreamergstreamer_oldjetsonNanokaggleLibrosnerfprueba.txtpytorchwallabotweb
We can move using relative paths if we only specify the direction starting from the point where we are located.
InputPythonterminal('cd web')Copied
InputPythonterminal('pwd')Copied
/home/wallabot/Documentos/web
Also, using relative paths we can go up one directory using ..
InputPythonterminal('cd ..')Copied
InputPythonterminal('pwd')Copied
/home/wallabot/Documentos
If instead of .. we use ., we are referring to the directory we are currently in, that is, if we type cd . we will not move, since we are telling the terminal to go to the directory we are already in.
InputPythonterminal('cd .')Copied
InputPythonterminal('pwd')Copied
/home/wallabot/Documentos
Let's move to a path where we have files to display the following command
InputPythonterminal('cd web/portafolio/posts/')Copied
InputPythonterminal('ls')Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translated__pycache__ssh.ipynbtest.htmltest.ipynb
File information with file
If I do not know what type of file one in particular is, using the file command I can obtain a description
InputPythonterminal('file 2021-02-11-Introduccion-a-Python.ipynb')Copied
2021-02-11-Introduccion-a-Python.ipynb: UTF-8 Unicode text, with very long lines
Manipulating files and directories
Letβs move first to the home.
InputPythonterminal('cd /home/wallabot/Documentos/')Copied
Directory tree with tree
We can see the entire folder structure we are in using the tree command
InputPythonterminal('tree', max_lines_output=20)Copied
.βββ 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.py873 directories, 119679 files
But the output shows too many lines, and this is because tree is a command that shows all the files from the path we are in, so it is a bit difficult to read. However, with the L option we can indicate how many levels we want it to go deep.
InputPythonterminal('tree -L 2')Copied
.βββ 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_rest30 directories, 12 files
We can see that it shows there are 30 directories and 12 files, whereas before it indicated 873 directories and 119679 files
Create folders with mkdir (make directory)
If we want to create a new directory, we can use the mkdir command (make directory) and a name
InputPythonterminal("cd /home/wallabot/Documentos/web/portafolio/posts/")Copied
InputPythonterminal('mkdir prueba')Copied
InputPythonterminal('ls')Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translatedprueba__pycache__ssh.ipynbtest.htmltest.ipynb
If what we want is to create a directory with spaces in its name, we have to put the name in quotation marks.
InputPythonterminal('mkdir "directorio prueba"')Copied
InputPythonterminal('ls')Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbdirectorio pruebaDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translatedprueba__pycache__ssh.ipynbtest.htmltest.ipynb
Let's go inside the prueba folder that we created, to keep looking there at the terminal
InputPythonterminal("cd prueba")Copied
Create files with touch
In case we want to create a file, the command we need to use is touch
InputPythonterminal("touch prueba.txt")Copied
InputPythonterminal("ls")Copied
prueba.txt
Copy files with cp (copy)
If we want to copy a file, we do it using the cp (copy) command
InputPythonterminal("cp prueba.txt prueba_copy.txt")Copied
InputPythonterminal("ls")Copied
prueba_copy.txtprueba.txt
Move files with mv (move)
If what we want is to move it, what we use is the mv (move) command
InputPythonterminal("mv prueba.txt ../prueba.txt")Copied
InputPythonterminal("ls")Copied
prueba_copy.txt
InputPythonterminal("ls ../")Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbdirectorio pruebaDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translatedpruebaprueba.txt__pycache__ssh.ipynbtest.htmltest.ipynb
Rename files with mv (move)
The mv command also serves to rename files, since if what we do is move it within the same directory, but giving it another name, in the end that is renaming the file.
InputPythonterminal("mv prueba_copy.txt prueba_move.txt")Copied
InputPythonterminal("ls")Copied
prueba_move.txt
Delete files with rm (remove)
To delete files or directories, we use the rm command (remove)
InputPythonterminal("rm prueba_move.txt")Copied
InputPythonterminal("ls")Copied
Remove directories with rm -r (recursive remove)
If what we want is to delete a directory with files inside, we must use the -r flag.
InputPythonterminal("cd ..")Copied
InputPythonterminal('rm -r "directorio prueba"')Copied
InputPythonterminal("ls")Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translatedpruebaprueba.txt__pycache__ssh.ipynbtest.htmltest.ipynb
As you can see, it never asks if we are sure; to make it ask, you need to add the -i (interactive) flag
InputPythonterminal("rm -i prueba.txt")Copied
rm: ΒΏborrar el fichero regular vacΓo 'prueba.txt'? (s/n) s
Sync files using rsync
So far we have seen how to copy, move, and delete files, but suppose we have a folder and we copy those files to another one. Now suppose we modify a file in the first folder and want the second one to have the changes. We have two options: copy all the files again, or perform a synchronization using rsync
First, we are going to create a new folder in which we will create several files
InputPython!mkdir sourcefolder!touch sourcefolder/file1 sourcefolder/file2 sourcefolder/file3Copied
Now we create a second folder, which is the one we are going to synchronize with the first one
InputPython!mkdir syncfolderCopied
InputPython!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolderCopied
ls sourcefolder:file1 file2 file3ls syncfolder:
We synchronize the two folders with rsync; the first time it will only copy the files from the first folder to the second. To do this, we must also add the -r (recursive) flag.
InputPython!rsync -r sourcefolder/ syncfolder/Copied
InputPython!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolderCopied
ls sourcefolder:file1 file2 file3ls syncfolder:file1 file2 file3
If I now create a new file in sourcefolder and synchronize again, only that file is copied to syncfolder. To see that only one file is copied, we can use the -v (verbose) flag.
InputPython!touch sourcefolder/file4Copied
InputPython!rsync -r -v sourcefolder/ syncfolder/Copied
sending incremental file listfile1file2file3file4sent 269 bytes received 92 bytes 722.00 bytes/sectotal size is 0 speedup is 0.00
But it seems that it has copied all the files, so to prevent this from happening and copy only the ones that have been modified, you need to use the -u flag
InputPython!touch sourcefolder/file5Copied
InputPython!rsync -r -v -u sourcefolder/ syncfolder/Copied
sending incremental file listfile5sent 165 bytes received 35 bytes 400.00 bytes/sectotal size is 0 speedup is 0.00
InputPython!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolderCopied
ls sourcefolder:file1 file2 file3 file4 file5ls syncfolder:file1 file2 file3 file4 file5
And what happens if I create a new file in syncfolder?
InputPython!touch syncfolder/file6Copied
InputPython!rsync -r -v -u sourcefolder/ syncfolder/Copied
sending incremental file listsent 122 bytes received 12 bytes 268.00 bytes/sectotal size is 0 speedup is 0.00
InputPython!echo "ls sourcefolder:" && ls sourcefolder && echo "ls syncfolder:" && ls syncfolderCopied
ls sourcefolder:file1 file2 file3 file4 file5ls syncfolder:file1 file2 file3 file4 file5 file6
It doesnβt sync, so itβs important to keep that in mind
Some important flags to keep in mind are:
-a: This flag is a shortcut for several options, including-r(recursive),-l(copy symbolic links),-p(preserve permissions),-t(preserve modification time), and-g(preserve group). This option is useful for making an exact copy of a directory, including all its subfolders and files.-v: This flag enables verbose output, showing the files being copied and the progress of the operation.-r: This flag is used to copy recursively, which means it copies all subfolders and files within a directory.-u: This flag is used to copy only new or modified files. If a file already exists at the destination and is newer than the source file, it is not copied.*-n: This flag is used to perform a dry run, which means no changes are made to the destination.--exclude: This flag is used to exclude specific files or folders from the copy operation. You can specify multiple files or folders to exclude by using this option several times.-z: This flag is used to compress data during transfer, which reduces the bandwidth used and speeds up the transfer rate.-h: this flag is used to display information in a more readable format, especially when working with large amounts of data or large file sizes.
We deleted the two created folders
InputPython!rm -r sourcefolder syncfolderCopied
Exploring the contents of the files
To avoid having to open a file from a graphical interface, we have several ways. Iβm going to copy a text file into this folder first.
InputPythonterminal("cd prueba")Copied
InputPythonterminal("cp ../2021-02-11-Introduccion-a-Python.ipynb .")Copied
InputPythonterminal("ls")Copied
2021-02-11-Introduccion-a-Python.ipynb
File headers with head
The first command to be able to look inside a text file is head, which allows us to see the first 10 lines of a file, but if you add the -n flag you can specify the number of lines
InputPythonterminal("head 2021-02-11-Introduccion-a-Python.ipynb")Copied
{"cells": [{"cell_type": "markdown","metadata": {"id": "dsaKCKL0IxZl"},"source": ["# IntroducciΓ³n a Python"]
InputPythonterminal("head -n 5 2021-02-11-Introduccion-a-Python.ipynb")Copied
{"cells": [{"cell_type": "markdown","metadata": {
File tail with tail
In case you want to see the last lines, we use tail
InputPythonterminal("tail 2021-02-11-Introduccion-a-Python.ipynb")Copied
},"vscode": {"interpreter": {"hash": "d5745ab6aba164e1152437c779991855725055592b9f2bdb41a4825db7168d26"}}},"nbformat": 4,"nbformat_minor": 0}
InputPythonterminal("tail -n 5 2021-02-11-Introduccion-a-Python.ipynb")Copied
}},"nbformat": 4,"nbformat_minor": 0}
If we want to continuously see the last lines of a file, for example, if we want to continuously monitor a LOG file to see events, we add the -f flag; this will keep the terminal continuously checking the file, and every time a new line appears in it, it will display it
For example, if I monitor the login log on my machine
InputPython!tail -f /var/log/auth.logCopied
Dec 1 16:27:22 wallabot gcr-prompter[1457]: Gcr: calling the PromptDone method on /org/gnome/keyring/Prompt/p2@:1.26, and ignoring replyDec 1 16:27:22 wallabot gnome-keyring-daemon[1178]: asked to register item /org/freedesktop/secrets/collection/login/10, but it's already registeredDec 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, quittingDec 1 16:27:33 wallabot gcr-prompter[1457]: Gcr: unregistering prompterDec 1 16:27:33 wallabot gcr-prompter[1457]: Gcr: disposing prompterDec 1 16:27:33 wallabot gcr-prompter[1457]: Gcr: finalizing prompterDec 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
We see in the last two lines my login when I turned on my computer today.
Now I connect via SSH to my own machine
InputPython!ssh localhostCopied
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/advantage1 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
In the console where the login was being monitored, two new lines have appeared
Dec 1 16:32:23 wallabot sshd[25647]: Accepted password for wallabot from 127.0.0.1 port 54668 ssh2Dec 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.
And when I close the SSH session, two new lines appear
Dec 1 16:33:52 wallabot sshd[25647]: pam_unix(sshd:session): session closed for user wallabotDec 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.
The most powerful file viewer: less
One of the most powerful commands for viewing inside files is less
InputPythonterminal("less 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)Copied
{"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}
Being inside a notebook, you cannot see what is really happening when using less, but when we use it we enter the document, and we can move through it using the keys or the mouse
If we want to search for something within the document, we type the / character and what we want to search for. To move between the different matches it has found, we press the n key, and if we want to go back through the searches, we press shift+n
To exit, just press q
The cat viewer
It does not allow you to navigate through the file or perform searches.
InputPythonterminal("cat 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)Copied
{"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}
Default system editor xdg-open
If we want to open it with the file's default editor, we have to use xdg-open
InputPythonterminal("xdg-open 2021-02-11-IntroducciΓ³n-a-Python.ipynb")Copied
File browser nautilus
If what we want is to open the folder we are in, we use nautilus
InputPythonterminal("nautilus")Copied
And if what we want is for it to open at a specific route, the route is included
InputPythonterminal("nautilus ~/")Copied
Word count of a file with wc (word count)
Finally, a very useful command is wc (word count), which shows you how many lines, words, and bytes a file has
InputPythonterminal("wc 2021-02-11-Introduccion-a-Python.ipynb")Copied
11678 25703 285898 2021-02-11-Introduccion-a-Python.ipynb
As we can see, the file has 11,678 lines, 25,703 words, and occupies 285,898 bytes
What is a command?
A command can be four things
- An executable program, these are usually stored in the
/usr/binpath - A shell command* A shell function
- An alias
To see which class a command belongs to, we use type
InputPython!type cdCopied
cd is a shell builtin
InputPython!type mkdirCopied
mkdir is /usr/bin/mkdir
InputPython!type lsCopied
ls is /usr/bin/ls
What is an alias?
An alias is a command that we define ourselves; it is defined using the alias command. For example, letβs create the alias l, which will run ls -h
InputPython!alias l='ls -l'Copied
When we run l, it shows us the result of ls -h
InputPython!lCopied
2021-02-11-IntroducciΓ³n-a-Python.ipynb
But this has the problem that when we close the terminal, the alias disappears. Later on, we will learn how to create permanent aliases
Command help
Help with help
With many shell commands, we can get their help using the help command
InputPython!help cdCopied
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 lavariable de shell HOME.La variable CDPATH define la ruta de bΓΊsqueda para el directorio quecontiene DIR. Los nombres alternativos de directorio en CDPATH seseparan con dos puntos (:). Un nombre de directorio nulo es igual queel 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 enlacessimbΓ³licos en DIR despuΓ©s de procesar las instancias de ".."-P usa la estructura fΓsica de directorios sin seguir los enlacessimbΓ³licos: resuelve los enlaces simbΓ³licos en DIR antes de procesarlas instancias de ".."-e si se da la opciΓ³n -P y el directorio actual de trabajo no sepuede determinar con Γ©xito, termina con un estado diferente de cero.La acciΓ³n por defecto es seguir los enlaces simbΓ³licos, como si seespecificara "-L".".." se procesa quitando la componente del nombre de la ruta inmediatamenteanterior hasta una barra inclinada o el comienzo de DIR.Estado de Salida:Devuelve 0 si se cambia el directorio, y si $PWD estΓ‘ definido comocorrecto cuando se emplee -P; de otra forma es diferente a cero.
Manual with man
Another command is man, which refers to the user manual.
InputPythonterminal("man ls", max_lines_output=20)Copied
LS(1) User Commands LS(1)NAMEls - list directory contentsSYNOPSISls [OPTION]... [FILE]...DESCRIPTIONList 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 optionstoo.-a, --alldo not ignore entries starting with .-A, --almost-all...Full documentation at: <https://www.gnu.org/software/coreutils/ls>or available locally via: info '(coreutils) ls invocation'GNU coreutils 8.30 September 2019 LS(1)
To exit, press q, since man uses less as the manual viewer
Information with info
Another command is info
InputPythonterminal("info ls", max_lines_output=20)Copied
File: coreutils.info, Node: ls invocation, Next: dir invocation, Up: Directory listing10.1 βlsβ: List directory contents==================================The βlsβ program lists information about files (of any type, includingdirectories). Options and file arguments can be intermixed arbitrarily,as usual.For non-option command-line arguments that are directories, bydefault βlsβ lists the contents of directories, not recursively, andomitting files with names beginning with β.β. For other non-optionarguments, by default βlsβ lists just the file name. If no non-optionargument is specified, βlsβ operates on the current directory, acting asif it had been invoked with a single argument of β.β.By default, the output is sorted alphabetically, according to thelocale settings in effect.(1) If standard output is a terminal, theoutput is in columns (sorted vertically) and control characters areoutput as question marks; otherwise, the output is listed one per line...β--show-control-charsβPrint nongraphic characters as-is in file names. This is thedefault unless the output is a terminal and the program is βlsβ.
To exit, press q, since info uses less as the information viewer
Information about a command with whatis
Another command is whatis
InputPythonterminal("whatis ls")Copied
ls (1) - list directory contents
Wildcards
Wildcards are special characters that help us perform special searches. For example, if I want to search for all files that end in .txt. Let's create a few files to see them.
InputPythonterminal("touch file.txt dot.txt dot2.txt index.html datos1 datos123 Abc")Copied
InputPythonterminal("ls")Copied
2021-02-11-Introduccion-a-Python.ipynbAbcdatos1datos123dot2.txtdot.txtfile.txtindex.html
All the characters *
Let's now look for all .txt files
InputPython!ls *.txtCopied
dot2.txt dot.txt file.txt
Let's now search for all those that start with the word datos
InputPython!ls datos*Copied
datos1 datos123
Numbers ?
But what happens if what we actually want is for it to show us all the files that start with the word datos but followed only by a number? We have to put a question mark ?
InputPython!ls datos?Copied
datos1
If what we want is for it to have three numbers, then we have to put three question marks ???
InputPython!ls datos???Copied
datos123
Uppercase [[:upper:]]
If we want it to look for files that start with uppercase letters
InputPython!ls [[:upper:]]*Copied
Abc
Lowercase [[:lower:]]
For files that start with lowercase letters.
InputPython!ls [[:lower:]]*Copied
datos1 datos123 dot2.txt dot.txt file.txt index.html
Classes
By using brackets, we can create classes. So if we want to search for files that start with the letters d or f followed by any character
InputPython!ls [df]*Copied
datos1 datos123 dot2.txt dot.txt file.txt
Redirections: how the shell works
A command works as follows
It has a standard input, which by default is the text we enter via the keyboard, a standard output, which by default is the text that appears in the console, and a standard error which is also, by default, text that appears in the console, but in a different format
Redirection of standard output
But with the character > we can modify the standard output of a command. For example, if we want to list with ls the files in the folder we are in, but we do not want the result to be printed on screen, but rather saved in a file, we would do the following ls > lista.txt, this writes the list in lista.txt. Also, if lista.txt does not exist, it creates it
InputPython!ls > lista.txtCopied
We can see that it has created the file and see what's inside
InputPythonterminal("ls")Copied
2021-02-11-Introduccion-a-Python.ipynbAbcdatos1datos123dot2.txtdot.txtfile.txtindex.htmllista.txt
InputPythonterminal("cat lista.txt")Copied
2021-02-11-Introduccion-a-Python.ipynbAbcdatos1datos123dot2.txtdot.txtfile.txtindex.htmllista.txt
We see that inside lista.txt appears lista.txt; that is because it first creates the file and then runs the command
We do the same, but with the parent folder
InputPython!ls ../ > lista.txtCopied
If we look again inside lista.txt
InputPythonterminal("cat lista.txt")Copied
2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translatedprueba__pycache__ssh.ipynbtest.htmltest.ipynb
We see that the content is overwritten
If what we want is for the content to be concatenated, we must use >>
InputPython!ls > lista.txtCopied
InputPython!ls ../ >> lista.txtCopied
InputPythonterminal("cat lista.txt")Copied
2021-02-11-Introduccion-a-Python.ipynbAbcdatos1datos123dot2.txtdot.txtfile.txtindex.htmllista.txt2021-02-11-Introduccion-a-Python.ipynb2021-04-23-Calculo-matricial-con-Numpy.ipynb2021-06-15-Manejo-de-datos-con-Pandas.ipynb2022-09-12 Introduccion a la terminal.ipynb2022-09-12 Introduccion a la terminal.txtcommand-line-cheat-sheet.pdfCSS.ipynbDocker.htmlDocker.ipynbExpresiones regulares.htmlExpresiones regulares.ipynbhtml_fileshtml.ipynbintroduccion_pythonmovies.csvmovies.datnotebooks_translatedprueba__pycache__ssh.ipynbtest.htmltest.ipynb
Now the information has been concatenated.
This is very useful for creating log files
Redirection of standard error
If we perform an incorrect operation, we get an error; let's see what happens when redirecting a command that produces an error
InputPython!ls fjhdsalkfs > lista.txtCopied
ls: no se puede acceder a 'fjhdsalkfs': No existe el archivo o el directorio
As we can see, it has given an error, but if we now look inside lista.txt
InputPythonterminal("cat lista.txt")Copied
We can see that the file is empty; that is because we have not redirected standard error to lista.txt, but rather standard output. As we saw in the image, there are two output streams in a command: the first is standard output and the second is standard error, so to redirect standard error you must indicate it with 2>. Let's do it now like this
InputPython!ls kjhsfskjd 2> lista.txtCopied
InputPythonterminal("cat lista.txt")Copied
ls: no se puede acceder a 'kjhsfskjd': No existe el archivo o el directorio
As we can see, it has now been redirected.
Redirection of standard output and standard error
If we want to redirect both of them, we use the following
InputPython!ls kjhsfskjd > lista.txt 2>&1Copied
Let's look inside lista.txt
InputPythonterminal("cat lista.txt")Copied
ls: no se puede acceder a 'kjhsfskjd': No existe el archivo o el directorio
If we now run a command without errors
InputPython!ls . >> lista.txt 2>&1Copied
Let's look inside lista.txt (**note**, we have now concatenated)
InputPythonterminal("cat lista.txt")Copied
ls: no se puede acceder a 'kjhsfskjd': No existe el archivo o el directorio2021-02-11-Introduccion-a-Python.ipynbAbcdatos1datos123dot2.txtdot.txtfile.txtindex.htmllista.txt
As can be seen, both the standard error and the standard output have been redirected to the same file
Pipelines
We can create pipelines by making the standard output of one command become the standard input of another. For example, we are going to make the output of ls -lha the input of grep, which we will see later, but it is a command for searching.
InputPython!ls -lha | grep -i "txt"Copied
-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
As we can see, what we have done is pipe the output of ls to grep, with which we have searched for any file with txt in the name
Control operators - chaining commands
Sequential commands
One way to chain commands sequentially is to separate them with ;. This creates different threads for each task
InputPython!ls; echo 'Hola'; calCopied
2021-02-11-Introduccion-a-Python.ipynb datos123 file.txtAbc dot2.txt index.htmldatos1 dot.txt lista.txtHolaDiciembre 2022do lu ma mi ju vi sΓ‘1 2 34 5 6 7 8 9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31
As we can see, first the ls command was executed, then Hola was printed thanks to the echo "Hola" command, and finally a calendar was printed thanks to the cal command
Let's now do another example to see that they are executed sequentially.
InputPython!echo "Before touch;"; ls -lha; touch secuential.txt; echo "After touch:"; ls -lhaCopied
Before touch;total 292Kdrwxrwxr-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.txtAfter touch:total 292Kdrwxrwxr-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
As can be seen, in the first ls sequential.txt does not appear, while in the second it does. That means the commands were executed in order, one after another
Parallel Commands
If what we want is for the commands to execute in parallel, we need to use the & operator. This will cause a new process to be created for each command.
Let's look at the previous example
InputPython!rm secuential.txtCopied
InputPython!echo "Before touch;" & ls -lha & touch secuential.txt & echo "After touch:" & ls -lhaCopied
Before touch;After touch:total 292Kdrwxrwxr-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
Now it can be seen that they have not been executed sequentially, since first the echos have been executed, which are the ones that take the least time, and then the rest.
Conditional Commands
And
Using the && operator, a command will execute when the previous one has executed successfully
InputPython!rm secuential.txtCopied
InputPython!echo "Before touch;" && ls -lha && touch secuential.txt && echo "After touch:" && ls -lhaCopied
Before touch;total 292Kdrwxrwxr-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.txtAfter touch:total 292Kdrwxrwxr-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
Here we can see how they have been executed one after another, that is, one command does not start until the previous one finishes
But then, what is the difference between ; and &&?
In the first case, the sequential ; means one command is executed first and then another, but for a command to run, it does not matter whether the previous one executed successfully.
InputPython!rm prueba ; ls -lhaCopied
rm: no se puede borrar 'prueba': No existe el archivo o el directoriototal 292Kdrwxrwxr-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
As can be seen, first rm prueba is executed, it gives an error and even so ls -lha prueba is executed
In the conditional form &&, if a command does not execute successfully, the next one is not executed.
InputPython!rm prueba && ls -lhaCopied
rm: no se puede borrar 'prueba': No existe el archivo o el directorio
As can be seen, ls -lha prueba is not executed because rm prueba has produced an error
Or
Unlike &&, or will execute all processes, regardless of their result. The || operator must be used.
InputPython!rm prueba || ls -lhaCopied
rm: no se puede borrar 'prueba': No existe el archivo o el directoriototal 292Kdrwxrwxr-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
The difference between this and ; is that || (or) does not create a new thread for each command
How permissions are handled
When listing the files in a directory with the -l (long) flag, some symbols appear next to each file.
InputPython!mkdir subdirectorioCopied
InputPython!ls -lCopied
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.txtdrwxrwxr-x 2 wallabot wallabot 4096 dic 6 01:10 subdirectorio
This gives us information about each file
First, letβs see what types of files there are
- -: Regular file
- d: Directory* l: Symbolic link
- b: Special block file. These are files that manage block data information, such as a USB drive.
Then we will see the types of mode:
```html
| Owner | Group | World | ||||||
|---|---|---|---|---|---|---|---|---|
| rwx | r-x | r-x | ||||||
| 1 | 1 | 1 | 1 | 0 | 1 | 1 | 0 | 1 |
| 7 | 5 | 5 | ||||||
- r: read
- w: write
- x: execute
Symbolic mode:
- u: For the user only
- g: Only for the group* o: Only for others (world)
- a: For all
Modifying permissions in the terminal
We created a new file
InputPythonterminal("cd subdirectorio")Copied
InputPython!echo "hola mundo" > mitexto.txtCopied
InputPython!cat mitexto.txtCopied
hola mundo
Let's see the permissions it has.
InputPython!ls -lCopied
total 4-rw-rw-r-- 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
As we can see, it has read and write permissions for my user and the group, and only read permissions for others (world).
Changing permissions with chmod (change mode)
To change the permissions of a file, we use the chmod (change mode) command, where we must specify in octal the permissions of the user, then those of the group, and finally those of everyone else.
InputPython!chmod 755 mitexto.txtCopied
InputPython!ls -lCopied
total 4-rwxr-xr-x 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
We see that now my user has read, write, and execute permissions, while the group and everyone else have read and execute permissions
Let's remove the read permissions only from my user. To change only a user's permissions, we use the symbolic identifier, a + if we want to add permissions, a - if we want to remove them, or an = if we want to reset them, followed by the permission type.
InputPython!chmod u-r mitexto.txtCopied
InputPython!ls -lCopied
total 4--wxr-xr-x 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
InputPython!cat mitexto.txtCopied
cat: mitexto.txt: Permiso denegado
As we can see, by removing read permissions for my user, we cannot read the file.
We give it the read permission again
InputPython!chmod u+r mitexto.txtCopied
InputPython!ls -lCopied
total 4-rwxr-xr-x 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
InputPython!cat mitexto.txtCopied
hola mundo
If we want to add or remove permissions for more than one user, we do it by separating each permission with a ,
InputPython!chmod u-x,go=w mitexto.txtCopied
InputPython!ls -lCopied
total 4-rw--w--w- 1 wallabot wallabot 11 dic 6 01:10 mitexto.txt
As can be seen, execution permission has been removed from the user, and write-only permission has been set for the group and everyone else.
User identification with whoami
To find out who we are, we can use the whoami command (who am I)
InputPython!whoamiCopied
wallabot
User information with id
Another way, which also provides more information, is the id command
InputPython!idCopied
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)
This command tells us that our user ID is 1000, the group ID is 1000, and that we belong to the groups wallabot, adm, cdrom, sudo, dip, plugdev, lpadmin, lxd, sambashare, and docker
Change user with the su command (switch user)
If we want to switch users, we use the su command (switch user). Depending on the user, we have to use sudo (superuser do).
InputPython!sudo su rootCopied
root@wallabot:/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio#
As we can see, the prompt changes and now indicates that we are the root user
Let's go to the home folder
InputPython!cdCopied
root@wallabot:~#
But in Linux there is a home folder for each user; we can see this if we run the pwd command
InputPython!pwdCopied
/root
Iβm going to create a file in the folder where I previously created the *mitexto.txt* file.
InputPython!touch /home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio/rootfile.txtCopied
I switch back to my user account
InputPython!su wallabotCopied
wallabot@wallabot:
And I go to the directory where the files I created are.
InputPython!cd /home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorioCopied
We see the files that are there and their permissions
InputPython!ls -lCopied
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
As we can see, the user and group of the *rootfile.txt* file are the user root
Yes, now that I am the *wallabot* user, I am trying to delete the file rootfile.txt
InputPython!rm rootfile.txtCopied
rm: ΒΏborrar el fichero regular vacΓo 'rootfile.txt' protegido contra escritura? (s/n)
As we can see, it asks us if we want to delete it, since it belongs to another user.
Change a userβs password
If I want to change the password of the user I currently have active, I use the passwd (password) command
First I check which user I am
InputPython!whoamiCopied
wallabot
And now we try changing the password
InputPython!passwdCopied
$ passwdCambiando la contraseΓ±a de wallabot.ContraseΓ±a actual de :Nueva contraseΓ±a:Vuelva a escribir la nueva contraseΓ±a
As we can see, it asks for the current password in order to change it.
Symbolic links
We can create symbolic links to a specific path using the ln (link) command followed by the -s (symbolic) flag, the directory, and the name of the link
InputPython!ln -s /home/wallabot/Documentos/web webCopied
If we now list the files
InputPython!ls -lCopied
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.txtlrwxrwxrwx 1 wallabot wallabot 29 dic 6 01:28 web -> /home/wallabot/Documentos/web
We see the symbolic link web pointing to /home/wallabot/Documentos/web:
I can now go to web
InputPythonterminal("cd web")Copied
InputPython!pwdCopied
/home/wallabot/Documentos/web
Configure the environment variables
View environment variables with printenv
With the printenv command, we can see all the environment variables
InputPython!printenvCopied
GJS_DEBUG_TOPICS=JS ERROR;JS LOGVSCODE_CWD=/home/wallabotLESSOPEN=| /usr/bin/lesspipe %sCONDA_PROMPT_MODIFIER=(base)PYTHONIOENCODING=utf-8USER=wallabotVSCODE_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=trueMPLBACKEND=module://ipykernel.pylab.backend_inlineSSH_AGENT_PID=1373XDG_SESSION_TYPE=x11SHLVL=0HOME=/home/wallabotCHROME_DESKTOP=code-url-handler.desktopCONDA_SHLVL=1DESKTOP_SESSION=ubuntuGIO_LAUNCHED_DESKTOP_FILE=/usr/share/applications/code.desktopVSCODE_IPC_HOOK=/run/user/1000/vscode-26527400-1.73.1-main.sockPYTHONUNBUFFERED=1GTK_MODULES=gail:atk-bridge...QT_IM_MODULE=ibusGIT_PAGER=catPWD=/home/wallabot/Documentos/webCLICOLOR=1XDG_DATA_DIRS=/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktopXDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdgVSCODE_CODE_CACHE_PATH=/home/wallabot/.config/Code/CachedData/6261075646f055b99068d3688932416f2346dd3bCONDA_EXE=/home/wallabot/anaconda3/bin/condaCONDA_PREFIX=/home/wallabot/anaconda3VSCODE_PID=3897
View an environment variable with the echo command
To see a specific environment variable, we can do it using the echo command followed by the $ symbol and the variable name
InputPython!echo $HOMECopied
/home/wallabot
Modify an environment variable for a terminal session
We can modify an environment variable for the active terminal session; for example, let's add a new path to the PATH variable. First, let's see what's in it.
InputPython!echo $PATHCopied
/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
Now we add a new directory
InputPython!PATH=$PATH:"subdirectorioCopied
Weβll look again at whatβs inside PATH
InputPython!echo $PATHCopied
/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
We see that the subdirectory directory has been added.
The problem with this method is that when we open a new terminal, this change in PATH will not be retained
Modify an environment variable for all terminal sessions
We're going to the home folder
InputPythonterminal("cd /home/wallabot")Copied
Here, on the home page, we list all files with the -a (all) flag
InputPython!ls -aCopied
. .eclipse .pki.. Escritorio Plantillas.afirma .gitconfig .platformioanaconda3 .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 .vscodeDescargas .mozilla .wget-hsts.docker MΓΊsicaDocumentos .nv
We see that there is a file called .bashrc; this file contains the configuration for our bash
InputPythonterminal("cat .bashrc", max_lines_output=3)Copied
# ~/.bashrc: executed by bash(1) for non-login shells.# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)# for examples...fiunset __conda_setup# <<< conda initialize <<<
This file is the one that configures the terminal every time a new one is opened, so if we edit the PATH variable in it, this change will remain for all new terminal windows we open
To modify the PATH variable within the configuration file, we need to add the following line to the file
PATH=$PATH:"subdirectory"Create alias for all sessions
We already saw how to create command aliases, but it also happened that they were lost every time we closed a terminal session. To prevent this from happening, we also added them to the .bashrc configuration file. For example, in my case I have added the following lines
alias ll='ls -l'
alias la='ls -a'
alias lh='ls -h'
alias lha='ls -lha'Search commands
Binary search with which
The first search command we are going to see is which, which allows us to find the path of binaries
InputPython!which pythonCopied
/home/wallabot/anaconda3/bin/python
However, if we look for something that is not in any of the PATH routes, which will not be able to tell us the path
InputPython!which cdCopied
File search with find
To search for a file with find, we need to indicate the path from which we want to search for the file, followed by the -name flag and the name of the file we want to search for.
InputPython!find ~ -name "2021-02-11-Introduccion-a-Python.ipynb"Copied
/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
As we can see, it is in your directory, plus the copy I created in this notebook and saved in the prueba folder
One very powerful thing about find is that we can use wildcards; for example, if I want to search for all the text files in my web folder.
InputPython!find ~/Documentos/web/ -name *.txtCopied
/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
If we do not want it to distinguish between uppercase and lowercase letters, we must use the -iname flag. For example, if we search for all files that contain the text FILE, but using the -iname flag.
InputPython!find ~/Documentos/web/ -iname *FILE*Copied
/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
We see that all the results contain file and not FILE, that is, it has not made a distinction between uppercase and lowercase letters
We can specify the file type with the -type flag. It only supports two types: f for files and d for directories.
InputPython!find ~/Documentos/nerf -name image*Copied
/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
InputPython!find ~/Documentos/nerf -name image* -type dCopied
/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
InputPython!find ~/Documentos/nerf -name image* -type fCopied
/home/wallabot/Documentos/nerf/instant-ngp/dependencies/tiny-cuda-nn/dependencies/fmt/doc/bootstrap/mixins/image.less
If we want to filter by file size, we can use the -size flag. For example, if we want to find all files larger than 200 MB
InputPython!find ~/Documentos/ -type f -size +200MCopied
/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
If we want to perform operations after the search, we use the -exec flag
For example, Iβm going to search for all folders named subdirectory
InputPython!find ~/ -name subdirectorio -type dCopied
/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio
Can I make them be deleted with the -exec flag
InputPython!find ~/ -name subdirectorio -type d -exec rm -r {} ;Copied
rm: ΒΏborrar el fichero regular vacΓo '/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorio/rootfile.txt' protegido contra escritura? (s/n) sfind: β/home/wallabot/Documentos/web/portafolio/posts/prueba/subdirectorioβ: No existe el archivo o el directorio
InputPython!find ~/ -name subdirectorio -type dCopied
Lastly, if we use the ! character, we will be indicating that it finds everything that does not match what we have specified
InputPython!find ~/Documentos/web/portafolio/posts/prueba ! -name *.txtCopied
/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
As we can see, it has found everything that is not a .txt
grep search command
grep is a very powerful search command, which is why we dedicate a section to it on its own. The grep command uses regular expressions, so if you want to learn about them, Iβll leave you a link to a post where I explain them
Let's start to see the power of this command; let's look for all the times the text MΓ‘ximoFN appears inside the file 2021-02-11-Introduccion-a-Python.ipynb
InputPythonterminal("cd /home/wallabot/Documentos/web/portafolio/posts/prueba")Copied
InputPythonterminal("grep MaximoFN 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)Copied
"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' ",
However, if we do the same search for the text maximofn
InputPython!grep maximofn 2021-02-11-Introduccion-a-Python.ipynbCopied
No results appear, this is because grep is case sensitive, that is, it looks for the text exactly as you entered it, distinguishing between uppercase and lowercase letters. If we do not want this, we have to add the -i flag
InputPythonterminal("grep -i MaximoFN 2021-02-11-Introduccion-a-Python.ipynb", max_lines_output=20)Copied
"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' ",
If what we want is for it to return the number of times it appears, we add the -c flag
InputPython!grep -c MaximoFN 2021-02-11-Introduccion-a-Python.ipynbCopied
105
If we donβt care whether it appears in uppercase or lowercase, we can add the -i flag again, but thereβs no need to add it separately from the -c flag; they can be used together.
InputPython!grep -ci MaximoFN 2021-02-11-Introduccion-a-Python.ipynbCopied
105
If now we want all the times in which **not** the word MΓ‘ximoFN appears, we add the -v flag
InputPython!grep -cv MaximoFN 2021-02-11-Introduccion-a-Python.ipynbCopied
11573
---
β‘οΈ **Continue in Part 2: networking, compression and processes**, where you will learn how to move around the network and control system processes.