Skip to content

Notas útiles que he recopilado en mi proceso de familizarme con Linux.

Notifications You must be signed in to change notification settings

DaryCC/notasutileslinux

Repository files navigation

Información que cura que me he econtrado por ahí

Tabla de contenido

find

find is one of the more powerful and flexible command-line programs in the daily toolbox, so it’s worth spending a little more time on it.

Perhaps you want to find all the JPEG files in your home directory. The -name argument allows you to restrict your results to files that match the given pattern.

find ~ -name '*jpg'

But wait! What if some of them have an uppercase extension? -iname is like -name, but it is case-insensitive.

find ~ -iname '*jpg'

You can combine patterns with and “or” , represented by -o.

find ~ ( -iname 'jpeg' -o -iname 'jpg' )

Pero qué pasa si hay directiorios con el nombre de jpg o JPEG, puede especificar que se muestren solo los archivos con type -f o type -d para directiorios.

find ~ ( -iname '*jpeg' -o -iname '*jpg' ) -type f

También se pueden hacer búsquedas de archivos basados en su fecha de modificación y creación, así como de su tamaño.

Puedes leer más aquí.

fzf

Algunos atajos

  • C Paste the selected files and directories onto the command-line .
  • C-R Paste the selected command from history onto the command-line
    • If you want to see the commands in chronological order, press CTRL-R again which toggles sorting by relevance
    • Set FZF_CTRL_R_OPTS to pass additional options
  • M-C cd into the selected directory
    • Set FZF_ALT_C_COMMAND to override the default command
    • Set FZF_ALT_C_OPTS to pass additional options

Uso

fzf will launch interactive finder, read the list from STDIN, and write the selected item to STDOUT.

find * -type f | fzf > selected

Without STDIN pipe, fzf will use find command to fetch the list of files excluding hidden ones. (You can override the default command with FZF_DEFAULT_COMMAND)

Using the finder:

  • CTRL-K / CTRL-J or (CTRL-P / CTRL-N) to move cursor up and down
  • Enter key to select the item, CTRL-C / CTRL-G / ESC to exit
  • On multi-select mode (-m), TAB and Shift-TAB to mark multiple items
  • Emacs style key bindings
  • Mouse: scroll, click, double-click; shift-click and shift-scroll on multi-select mode

xrandr

Para configurar multiples monitores.

Utilidades para instalar

  • Exa, alternativa moderna a ls
  • bat, alternativa moderna a cat
  • ghq , manage local git repositories
  • fuck, plugin para zsh, evalua el commnado sugerido, agrega –yeah para confirmar automáticamente.
  • copypath, zsh
  • copyfile,zsh

Web-mode

HTML Tags

fold/unfold

C-c C-f

Spacemacs useful resources

Multiline editing

Visual mode for selection of block

- C-v
- Cursor down (j, down)
- I (insertion mode)
- ESC (exit visual mode)

Lee sobre evil-mode or el manual de Vim para más detalle.

iedit

- *
- e (iedit)
- SPC s e
- ESC (exit iedit)

The ocurrence can be toggled with the TAB key.

You can move cursor easily by using n or N

Iedit provides several way to restric the scope. For example, to restrict the scope to the function, just press f.

Reaad the iedit manual.

<div id="root">
    <li>Nadia</li>
    <li>Madia</li>
    <li>Radia</li>
    <li>Padia</li>
</div>

<div id="root">
    <li class="prueba">Nadia</li>
    <li class="prueba">Madia</li>
    <li class="prueba">Radia</li>
    <li class="prueba">Padia</li>
</div>

<div id="root">
    <li class="prueba2">Nadia</li>
    <li class="prueba2">Madia</li>
    <li class="prueba2">Radia</li>
    <li class="prueba2">Padia</li>
</div>

Magit

Algunas notas son tomadas de:https://systemcrafters.net/mastering-git-with-magit/everyday-git-workflow/

Setting a new local repo to github

At local repo

git init -b main
git add . && git commit -m "initial commit"

Create a new local repository in github

In terminal, add the URL for the remote repository

$ git remote add origin  <REMOTE_URL>
git remote add origin git@github.com:user/repo.git
# Sets the new remote
$ git remote -v
# Verifies the new remote URL

Push the changes

$ git push origin main
# Pushes the changes in your local repository up to the remote repository you specified as the origin

By using Magit

M (remote) a (add). It will ask you for the name (origin) and the URL.

Example:

Remote name: origin Remote url: git@github.com:DaryCC/bashscript.git

Push Branch to Another Branch

git push <remote> <local_branch>:<remote_name>

Clean Your Commits Like a Git Rebase Expert with Magit

ve el video aquí

Rebase TL;DR versión

git checkout feature1
git rebase master
#solver conflict and then add .
git add file1
git rebase --continue
# Applying: D
git log --all --decorate --graph
git rebase --continue

Before rebase:

Magit/2022-06-21_04-12-48_rebase1.png

After rebase:

Magit/2022-06-20_14-48-06_rebase2.png

After rebase: merging and fast-forwarding

git checkout master
git merge feature1
git log --all --decorate --graph

Magit/2022-06-20_14-55-46_rebase3.png

Have you ever made a mistake or created sloppy commits when checking in changes to a Git repository?

After watching this video, you’ll know exactly how to fix those problems and create a clean commit history with git rebase and Magit. Example repository needed

Cherry pick

Magit/2022-06-20_15-00-20_cherry_pick.png

#para obtener el id del commit deseado de la rama feature
git log --all --oneline --decorate --graph
git checkout master
git cherry-pick ID
#git status si hay conflictos, resuelve
git add .

git bisect

Es una búsqueda binaria de errores,usualmnete se usa para encontrar bugs medianta la selección de commits buenos y malos.

Magit/2022-06-20_15-07-09_bisect.png

En este caso se una un test:

#! /bin/bash
if grep 63 projectfile
then
    echo BAD
else
    echo GOOD
fi
git bisect start
./test.sh
git bisect bad
git status
git checkout HEAD~99
git status
./test.sh
git bisect good
git log

Difference between reported commit and its parent.

git diff 37cfc7e407bb20392f067f07899c1c0bf8b94560^ \37cfc7e407bb20392f067f07899c1c0bf8b94560

Rules of thumb

The ^ operator is

  • Use \~ most of the time — to go back a number of generations, usually what you want
  • Use ^ on merge commits — because they have two or more (immediate) parents

Mnemonics:

  • Tilde \~ is almost linear in appearance and wants to go backward in a straight line
  • Caret ^ suggests an interesting segment of a tree or a fork in the road a handy shortcut that allows you to quickly refer to a commit’s parent.

Reviewing commits

SPC g s magit-status

An important tip!

Here’s something I recommend before doing any rebase operation if you’re not that familiar with it yet.

Back up your branch before the rebase just to make sure you won’t lose access to the original commits!

In the magit-status buffer you can press b n to create a new branch. It will ask you the source branch and the name for the target branch.

Now that we have our backup branch, we can always get the original commits back if we make a mistake!

Rewording commits

You can reword any commit in your branch’s history by performing an interactive rebase using Magit.

In the magit-status buffer, put your cursor on the commit you want to reword and press r i (lower-case R then I). This will bring up a rebase interface which displays the list of commits starting at the selected commit to allow you to pick which operation to take on each of them.

For the commit we want to reword, we can put our cursor on its line and press r ((lower-case R)) and it will be marked as reword. Press C-c C-c to confirm.

You will now be given a commit message editing buffer to fix the wording of the commit. Make your changes and press C-c C-c to confirm and C-c C-k to cancel
Nota: no funcionan los comandos en el buffer de Spacemacs, puedes editar manualmente las operaciones

Luego de editar las operaciones, usa rebase continue r c.

Se van a hacer cambios en el log history, por lo que existirá un conflicto entre la repo local y remota, por lo que se tendrá que hacer un force push.

You just changed history!

Keep in mind that editing any commit in the history will cause all following commits to be recreated so they will all have a new commit hash! This means that you will need to force push your changes to the remote repository if you have already pushed the branch there once before.

Reordering commits

The commit history you create can be seen as the story of the code’s creation. Sometimes it makes sense for a more recent change to be moved back before other changes to improve the narrative.

You can reorder commits easily in the interactive rebase view by placing the cursor on a particular commit and using the following key bindings:

  • M-n / M-j (evil): Move the commit forward in time by one commit
  • M-p / M-k (evil): Move the commit backward in time by one commit

You can reorder multiple commits in one interactive rebase operation!
Nota: en Spacemacs funciona M-n y M-p.

Resolving magit conlflictsealing with conflicts when moving commits

Since there’s a conflict in the changes of both commits, we need to edit the file to resolve the issues. Once we’ve finished the edit the changes will be automatically staged and we can use r r (two lower-case r) to continue the rebase.

We’ll be asked to edit and confirm the commit message. We don’t need to add any changes so we can use C-c C-c to complete the commit.

We’ll also have to deal with another conflict! Let’s add the function back in the next commit and continue from there.

NOTE: No uses commit manualmente, úsalo con el la operación rebase.
If the merge is looking too complicated and you want to start over, you can use r a to abort the current rebase!

g to refresh the current buffer G to refresh all buffers

press SPC g v r, quit with q

press SPC g s, e for magit ediff quit with q

n/p to move to next/previous conflicts

a/b to chose wich changes (those in a A or B) should be the ones to keep in the merged file.

You can always just switch to buffer C and edit what the merged version should look like

By using Smerge, just pres RET in magit status,

  • C-c ^ RET smerge-keep-current
  • C-c ^ = Prefix Command
  • C-c ^ C smerge-combine-with-next
  • C-c ^ E smerge-ediff
  • C-c ^ R smerge-refine
  • C-c ^ a smerge-keep-all
  • C-c ^ b smerge-keep-base
  • C-c ^ l smerge-keep-lower
  • C-c ^ m smerge-keep-upper
  • C-c ^ n smerge-next
  • C-c ^ o smerge-keep-lower
  • C-c ^ p smerge-prev
  • C-c ^ r smerge-resolve
  • C-c ^ u smerge-keep-upper
  • C-c ^ = < smerge-diff-base-upper
  • C-c ^ = = smerge-diff-upper-lower
  • C-c ^ = > smerge-diff-base-lower

Rebase config

warning: Pulling without specifying how to reconcile divergent branches is
discouraged. You can squelch this message by running one of the following
commands sometime before your next pull:

  git config pull.rebase false  # merge (the default strategy)
  git config pull.rebase true   # rebase
  git config pull.ff only       # fast-forward only

You can replace "git config" with "git config --global" to set a default
preference for all repositories. You can also pass --rebase, --no-rebase,
or --ff-only on the command line to override the configured default per
invocation.

remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), 51.49 KiB | 850.00 KiB/s, done.

When you do a git pull origin master, git pull performs a merge, which often creates a merge commit. Therefore, by default, pulling from the remote is not a harmless operation: it can create a new commit SHA hash value that didn’t exist before. This behavior can confuse a user, because what feels like it should be a harmless download operation actually changes the commit history in unpredictable ways.

To avoid this, you need git pull --ff-only With git pull --ff-only, Git will update your branch only if it can be “fast-forwarded” without creating new commits. If this can’t be done, git pull --ff-only simply aborts with an error message.

You can configure your Git client to always use --ff-only by default, so you get this behavior even if you forget the command-line flag:

git config --global pull.ff only

Differences between git pull origin master & git pull origin/master

git pull origin master will pull changes from the origin remote, master branch and merge them to the local checked-out branch.

git pull origin/master will pull changes from the locally stored branch origin/master and merge that to the local checked-out branch. The origin/master branch is essentially a “cached copy” of what was last pulled from origin, which is why it’s called a remote branch in git parlance. This might be somewhat confusing.

You can see what branches are available with git branch and git branch -r to see the “remote branches”.

Not possible to fast-forward even with no changes

$ git pull -v --ff-only
From github.com:username/repo
 = [up to date]      branch    -> origin/branch
 = [up to date]      branch2    -> origin/branch2
 = [up to date]      branch3    -> origin/branch3
fatal: Not possible to fast-forward, aborting.

Your commits on your ‘develop’ branch do not match the commits on your ‘origin’ branch. Do this:

git pull origin develop --rebase

Editing a commit

We’ll need to make a tweak to the following commit to restore the use of the new filet-new-recipe in the filet-add-recipe command since we had to remove it when resolving the previous conflicts.

Let’s start a new interactive rebase and use the edit command on that commit by pressing e with the cursor on that line.

Ahora puedes editar el código en el commit o punto seleecionado.

We can now go and change the code however we like and then stage those changes to be added to the existing commit.

In the magit-status screen press r r to complete the rebase operation.

Combining commits

Magit/2022-06-20_19-06-24_squash.png

Now we’re going to see how we can combine two commits together. There are two ways to do this:

  • fixup: Merges only the changes of a commit into the previous commit
  • squash: Merges the changes of a commit into the previous commit and combines their commits messages

Nota: usa fixup si no te importa el mensaje del commit.
Para squash y fixup deja un commit base sobre el que se van a encimar el resto de los commits.

Deleting commits

Sometimes you will make temporary commits that are only useful for debugging purposes or maybe diagnosing a test failure in your CI runs.

Before you merge your branch, you will probably want to delete these commits! Thankfully interactive rebase makes this easy.

Start a new interactive rebase at the commit that you want to delete. We can press the k key to use the drop operation on the temporary commit and then press C-c C-c to confirm and then the commit will be deleted! (evil-collection users will need to press d instead). Nota: Borra un commit anterior del deseado, usa rebase.

Let’s do it all at once!

Now that we know the whole flow, let’s clean up the same commits all in one interactive rebase!

Here’s the point where the backup branch we created becomes useful.

Inside the magit-status screen we can press O (capital letter ‘O’) to open the Reset panel. evil-collection users will need to press O (capital letter ‘O’) instead!

We will then press h (lower-cased ‘H’) to select the Hard option. In this case, a hard reset will set our working tree back to the state of the source we select.

We can now select our add-recipes-backup branch to reset the add-recipes branch back to its previous history!

Now let’s start the interactive rebase process again and perform all the changes we saw so far in one operation.

Adding a file or change to the most recent commit

Para agregar algunos cambios al commit anterior al estado actual, se puede usara la opción Extend pulsando la combinación c-e, usa la combinación C-c C-c para confirmar o C-c C-k para cancelar.

Nota: Los nuevos commits se agregan al contenido del commit anterior, por lo que el diff cambia pero el log (mensaje del commit se mantiene), en otra palabras se creo un nuevo commit con un log history diferente.
Para editar los mensajes los mensajes del commit cuando se agregen nuevos archivos se puede usar la opcioón Amend , presiona C-c C-c para confirmar o C-c C-k para abortar la edición.\ If you only want to edit the commit message without adding any staged changes, use c w (Commit -> Reword).

NOTE: If you’ve already pushed the original commit to a remote branch, you’ll have to force-push the branch the next time because the commit histories won’t match! .

Adding a file or change to a specific commit

Maybe you’ve already made other commits after the commit you need to edit, how can you add new changes to the earlier commit?

On the command line, you would normally use git rebase to accomplish this, which is generally considered to be a more advanced Git technique.

Luckily Magit makes this specific operation much simpler with the Instant Fixup feature!

To add changes to an earlier commit, just stage them like you normally would and then press c F (Commit -> Instant Fixup).

You’ll be presented with Magit’s commit log view which shows the current branch’s commits with the newest commits sorted first. Just move your cursor to the line of the commit you want to edit and press C-c C-c and the changes will be added to this commit!

NOTE: Like we talked about before, any operation that changes an existing commit will require you to force-push the branch!

Create a new branch from the changes of the current branch

Magit has a really convenient interface for creating branches through M-x magit-branch or the b key in the magit-status buffer.

One of my favorite Magit features is here: it allows you to create a new branch with the changes you already committed to the current branch while putting the original branch back to the commit where it started.

Imagine this scenario: you’ve been working on some changes for a while, making commits without really thinking about where you’ve been committing them. It turns out you’ve been committing them to the main/master branch all along!

To create a new branch with all these commits while putting the original branch back to its previous state, you can run M-x magit-branch-spinoff or press lower-cased b s inside of the status buffer. It will ask you for the name of the new branch and then create it, resetting master back to the commit before your new commits were added.

NOTE: This only works when the branch you’re starting from has been pushed to the remote!

We can then use b b in the status buffer to switch back to master to confirm that it has been rolled back to the original commit! Once we’re satisfied with that, we can use b b again to select the new branch we created.

Pushing a local branch to a remote

commits to a remote location (like GitHub) so that you can share or collarborate Once you’ve made a few commits to a branch, you’ll eventually need to push those with others.

Magit has a very convenient interface for this which enables you to do all the things you might do on the command line with just a few key presses:

Pushing a new local branch to a remote

Usually when you create a new branch, there won’t be a matching branch on the remote repository yet.

To push the new branch we created, we can press P p (upper-cased ‘P’ then lower-cased ‘p’) while in the magit-status buffer.

This will create the branch on the remote called origin and push the commits from the local branch to this new remote branch.

You can also see that the “Push:” entry in the repo status section at the top of the status buffer now mentions the remote branch!

Pushing new changes to an existing branch

If you make a new commit on the current branch, you can push it to the same remote branch by pressing P p in the status buffer again.

Magit remembers the branch that you pushed to the last time so you can always use P p to push there again!

Pushing a branch that has had its commits modified

In a couple of examples before, I showed how you can edit existing commits by adding more changes or rewording the commit message.

If you’ve done this, the only way to push those changes to the same branch is to use the -f argument when you launch the Push panel with P!

NOTE: Enabling this option will overwrite the remote branch with the commits in the local branch, so make sure you are only force-pushing to a branch that is not main or master! Changing the commit history makes it really difficult for collaborators to pull your changes.

Saving local changes for later

There will be times where you’ll need to move uncommitted local changes out of the way so that you can perform some other Git operation like a pull or rebase.

Git provides a command for this called git stash, it basically saves your uncommitted changes and clears them from your local folder so that they don’t show up in git status any longer.

In Magit, you can stash changes from the magit-status buffer by pressing z z (Stash -> Both This). will create a local stash entry for those changes after prompting you for a description for the stash.

You can now view the stashed changes by expanding the Stashes list on the status buffer.

You can restore the latest stash by running z p (Stash -> Pop) which will restore the stashed changes and delete the stash entry. If you want to keep the stash entry around you can use z a (Stash -> Apply) instead!

Pulling new commits from a remote into a local branch

Regardless of whether you’re working on your dotfiles repo or collaborating with others on a project, you’ll eventually need to pull commits from a remote repository.

From the magit-status buffer, you can press the F key to open the Pull panel.

To pull any new changes from the remote version of the current local branch, you can press p (or F p from the status buffer) to pull the latest commits from the remote.

This will fetch the latest commits from the selected remote and then attempt to pull them into the current branch!

If you receive an error saying that there are uncommitted local changes, use the z z (stash) command we talked about before to stash those local changes before pulling the remote changes!

Rebasing local changes onto the new commits

You’ll inevitably need to pull new commits from another branch (like main or master) into your current branch before you can merge it back into the main branch.

You can easily do this by turning on the rebase option in the Pull panel by pressing the r key: F r. Now when you pull this branch, the commits you’ve made will be replayed on top of the branch you are pulling from.

If your changes apply cleanly to the changes you’re pulling from the remote branch, everything should finish smoothly! However if there are merge conflicts with the new commits, you will need to make edits to fix those before you can proceed with the rebase.

After all merge markers have been cleaned up and all files are staged, you can press r r to continue the rebase operation and C-c C-c to confirm the updated commit.

We’ll cover how you can deal with merge conflicts in the next episode of this series! I’ll also describe git rebase in more detail since this is only a very brief introduction to it.

Fetching without pulling changes

If you merely want to fetch the latest branches and commits from the remote repository without pulling them into your local branch, you can follow a different path:

Open magit-status and press f p to fetch the origin repository or f u to fetch from the configured upstream repository. You will now be able to check out branches or list commits from the remote!

Discarding unwanted changes

Let’s say you’ve been making changes in your repo that you later decide that you no longer need. Instead of going back to those files to undo the changes, you can use the Discard action of the status buffer to get rid of them!

In the status buffer, you can put your cursor on any file, hunk, or line and press k to discard the change. Typically you will be prompted to confirm before it actually gets discarded.

NOTE: If you’re using evil-collection with evil-mode, the key will be x instead!

This also works for untracked files! This is usually faster than going to the command line to delete the unwanted files.

Adding a file to .gitignore

Perhaps you’ve got a file in the repository that you never want to see in the Untracked Files section because it doesn’t belong in the repository. Normally you’d add that to your .gitignore file in the repo.

Magit can help with this! Put your cursor on the file and press i to raise the Gitignore panel which has 3 options:

  • t: Add the file to the repo-level .gitignore file
  • s: Add the file to a .gitignore file in the folder where the file lives
  • p: Ignore the file “privately” in your local clone of the repo without editing .gitignore

Upon pressing any of these keys, you’ll be prompted for the actual file pattern to add to the ignore file, usually the first suggestion is the one you should use!

Magit will now create the .gitignore file if it doesn’t exist and then add it to Staged Changes for you. Just commit the file to make the change permanent!

What’s next?

In the next video, I’ll show you how to do even more advanced Git operations like rebasing, cherry picking, and managing the reflog. If you’re a programmer that uses Git to collaborate with others on a daily basis, Magit will make your life a lot easier!

If you have any questions about what we covered today, leave a note in the comments!

Support Jonas on GitHub sponsors: https://github.com/sponsors/tarsius

Three ways to Discard/Revert Git commits

velo aquí

Hard reset

In the Magit status buffer, select the desired commit Id and then press O h to Nota: con este método se borran todos los logs y commits, tal vez se tenga que usar un force push debido a que se modificaron los registros.

Revert

  1. b b to checkout a brach hard reset.
  2. Selecciona los commits que quieres revertir, uno antes del deseado.
  3. _ _ to revert commits. C-c C-c to confirm it.
  4. Si te sale opción replay the change relative to the specified parent, especifica 1, es para seleccionar parent quieres revertir el merge.
  5. Si existe algún conflicto puedes usar r (continue) o s (Skip) a (abort)
  6. Para comprobar que se revirtieron los cambios anteriores usa diff para comparar el último commit con el commit al que se quiere revertir.
    d r to diff a range. Nota: con este método se generan nuevos commits o logs por cada commit revertido. Se crean nuevos logs/registros.

Selecciona hasta los commits excluyendo el commit deseado.

Si existe algún conflicto luego de realizar los cambios y pushear el repo remoto usa -f force with lease

Soft reset

Puedes auxiliarte de Log all branches l b para seleccionar el Id de un commit.

  1. Selecciona el commit y presiona O s en Spacemacs o X s en vanilla Emacs para hacer soft reset.
  2. Se genera nuevos logs por commit restaurados, tambien puedes auxiliarte de diff.
  3. Commit

Notas: Los cambios echos o en stage se conservan, y los archivos untracked no se modifican tampoco.

Delete local and remote branch

TL;DR

#first checkout main branch
# git branch -d <branch>.
git branch -d fix/authenticatio
# git push <remote> --delete <branch>
git push origin --delete fix/authentication
#or
# git push <remote> :<branch>
git push origin :fix/authentication
git fetch -p

Magit

Type y or y r (magit-show-refs) to go to the refs buffer, and then x or k on vanilla Emacs (magit-branch-delete) on any remote branch to delete it.
Type b x.

About

Notas útiles que he recopilado en mi proceso de familizarme con Linux.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published