Comandos básicos de bash, git, npm y yarn, así como un poco sobre package.json y semver

¡Buen dia amigos!



Aquí hay una pequeña hoja de trucos para los comandos básicos bash, git, npm, yarn, package.json y semver.



Leyenda: [dir-name] - significa el nombre del directorio, | - significa "o".



Recomiendo ingresar cada comando en la terminal y estudiar cuidadosamente el resultado, para que los recuerde rápidamente y determine qué comandos necesita y cuáles no.



Pido disculpas por los posibles errores y errores tipográficos. Estaré encantado de recibir comentarios y sugerencias.



Sin más preámbulos.



Tabla de contenido:





intento



bash es una herramienta de línea de comandos que le permite hacer algunas cosas comunes.



Instalación: En mi caso, bash se instaló junto con git.



Referencia:



help


Historial de comandos:



history


Limpieza de terminales:



clear


Saliendo de la terminal:



exit


Creación de directorio:



// make directory
mkdir [dir-name]
// 
mkdir my-app
//  
mkdir -p {dir1,dir2}
//   
mkdir -p my-app/{css,js}


Cambio de directorio:



// change directory
cd [dir-name]
// 
cd my-app
//   
cd !$
//  
cd ..
//    
cd ../..
//  
cd -
//  
cd ~


La ruta al directorio actual:



// print work directory
pwd


Lista de archivos:



// list
ls
//   
ls -a | -f
//  
// ,  
ls -l


Creación de archivos:



touch [file-name]
// 
touch index.html
//  
touch my-app/{index.html,css/style.css,js/script.js}


Contenido del archivo:



cat [file-name]
// 
cat index.html
//     
cat [file-name] | sort | uniq
//  
less [file-name] // q - exit
// n    
head -50 [file-name]
// n    
tail -50 [file-name]
//  
grep [string] [file-name]

//     
unzip [achive-name]

//  
file [file-name]


Copiar, mover y eliminar un archivo:



// copy
cp [file1] [file2]

// move
mv [file1] [file2]
// 
//        
mv [dir1]/*.* [dir2]

// remove
rm [file-name]
//   
rmdir [dir-name]
//   
rm -r [dir-name]
// 
rm -rf [dir-name]


Salida al terminal de la línea:



echo [string]
// 
echo hello
//    
echo hello > greet.txt
//    
echo hello >> greet.txt


Subir archivo:



wget [url]


Conectores:



true && echo hello
false || echo hello
echo hello ; ls


Transportador:



//    - \n
cat [file] | wc -l


git



git es un sistema de control de versiones distribuido que le permite controlar el proceso de realizar cambios en un proyecto.



Libro Pro Git .



Proyección de Ilya Kantor .



Inicio rápido: Git How To .



Instalación: git-scm.com .



Comprobación de la instalación:



git --version


Referencia:



git help
git help [command-name]
git [command-name] --help | -h


Configuraciones mínimas:



// --local -    
// --global -    
// --system -    , ..   
git config --global user.name "My Name"
git config --global user.email "myemail@example.com"


Ajustes adicionales:



//   
git config --list | -l --global

//   
git config --global --edit | -e


Creando un repositorio:



git init


Limpiar el repositorio:



// -d -  , -x -   , -f - 
git clean | -dxf


Eliminar archivos y directorios:



// remove
git rm [file-name]
git rm -r [dir-name]

git rm --force | -f


Mover archivos:



// git add + git remove
// move
git mv [old-file] [new-file]


Ver el estado del repositorio:



git status


Añadiendo cambios:



git add [file-name]

git add --force | -f

//  
git add . | --all | -A

//           .gitkeep


Agregar un mensaje (confirmar):



//  
git commit

//    ,    git add . | -A
//  ,      
git commit --message | -m "My Message"

//   ,  git add [file-name]   
git commit --all | -a -m | -am "My Message"

//  
git commit --amend "My Message" | --no-edit


Ver confirmación:



//  
git show

//  
git show [hash] //   4 

//       
git show :/[string]

//    
git show [tag-name]


Viendo la diferencia entre confirmaciones:



git diff HEAD | @ // HEAD -  ,  ; @ -   HEAD

// staged
git diff --staged | --cached

git diff [hash1] [hash2]

//   
git diff [branch1]...[branch2]

//       
git commit --verbose | -v

//   
git diff --word-diff | --color-words


Ver historial de cambios:



git log

// n -  
git log -n
// --since, --after - 
// --until, --before - 

// 
git log -p

//  
git log --graph --oneline --stat

//  
git log --pretty=format
// 
git log --pretty=format:'%C(red)%h %C(green)%cd %C(reset)| %C(blue)%s%d %C(yellow)[%an]' --date=short | format-local:'%F %R'

//    , , ; i -   
git log --grep | -G [string] | [file] | [branch] & -i

//    
git log --grep [string1] --grep [string2] --all-match

//     
git log -L '/<head>/','/<\/head>/':index.html

//   
git log --author=[name]


Cancelación de cambios:



git reset
// --hard -     
// --soft -     
// --mixed -  :   ,   

git reset --hard [hash] | @~ // @~ -    HEAD

// 
git reset --hard ORIG_HEAD

//     
git checkout

git restore


Trabajando con sucursales:



//  
git branch

//  
git branch [branch-name]

//   
git checkout [branch-name]

// branch + checkout
git checkout -b [branch-name]

// 
git branch -m [old-branch] [new-branch]

//  
git branch -d [branch-name]

//  
git merge [branch-name]


Resolución de conflictos de fusión:



// ,   ,  

//     
git checkout --ours

//     
git checkout --theirs

//  
git reset --merge
git merge --abort

//   
git checkout --conflict=diff3 --merge [file-name]

//  
git merge --continue


Repositorio remoto:



// 
git clone [url] & [dir]

// 
git remote
git remote show
git remote add [shortname] [url]
git remote rename [old-name] [new-name]

//  
// git fetch + git merge
git pull

//  
git push


Etiquetas:



// 
git tag

//  
git tag [tag-name]
//
git tag v1-beta

//  
git tag -a v1 -m "My Version 1"

// 
git tag -d [tag-name]


Depuración



git bisect

git blame

git grep


Guardar cambios no confirmados:



// 
git stash

// 
git stash pop


Copiando una confirmación:



git cherry-pick | -x [hash]

//   
// 
git cherry-pick --abort

// 
git cherry-pick --continue

git cherry-pick --no-commit | -n

// --cherry = --cherry-mark --left-right --no-merges
git log --oneline --cherry [branch1] [branch2]


Reubicación:



git rebase [branch]

//   
// 
git rebase --abort

// 
git rebase --skip

// 
git rebase --continue

//   
git rebase --preserve-merges | -p

//  
git rebase -i [branch]


Autocompletar conflictos duplicados:



// rerere - reuse recorder resolution
// rerere.enabled true | false
// rerere.autoUpdate true | false
// rerere-train.sh -    rerere
git rerere forget [file-name]


Compromisos inversos:



git revert @ | [hash]

//  
// git reset --hard @~  
git revert [hash] -m 1

// git merge [branch]  
//  
git revert [hash]

//    rebase
git rebase [branch1] [branch2] | --onto [branch1] [hash] [branch2]

git merge [branch]

git rebase [hash] --no-ff


Un ejemplo de alias (atajos) para .gitconfig:



[alias]
    aa = add -A
    co = checkout
    ci = commit -m
    st = status
    br = branch


Ejemplo .gitconfig:
[user]
	name = [My Name]
	email = [myemail@example.com]
	username = [myusername]
[core]
	editor = [myeditor]
	whitespace = fix,-indent-with-non-tab,trailing-space,cr-at-eol
	pager = delta
[web]
	browser = google-chrome
[instaweb]
	httpd = apache2 -f
[rerere]
	enabled = 1
	autoupdate = 1
[push]
	default = matching
[color]
	ui = auto
[color "branch"]
	current = yellow bold
	local = green bold
	remote = cyan bold
[color "diff"]
	meta = yellow bold
	frag = magenta bold
	old = red bold
	new = green bold
	whitespace = red reverse
[color "status"]
	added = green bold
	changed = yellow bold
	untracked = red bold
[difftool]
	prompt = false
[delta]
	features = line-numbers decorations
	line-numbers = true
[delta "decorations"]
	minus-style = red bold normal
	plus-style = green bold normal
	minus-emph-style = white bold red
	minus-non-emph-style = red bold normal
	plus-emph-style = white bold green
	plus-non-emph-style = green bold normal
	file-style = yellow bold none
	file-decoration-style = yellow box
	hunk-header-style = magenta bold
	hunk-header-decoration-style = magenta box
	minus-empty-line-marker-style = normal normal
	plus-empty-line-marker-style = normal normal
	line-numbers-right-format = "{np:^4}│ "
[github]
	user = [username]
	token = token
[gitflow "prefix"]
	versiontag = v
[sequence]
	editor = interactive-rebase-tool
[alias]
	a = add --all
	ai = add -i
	###
	ap = apply
	as = apply --stat
	ac = apply --check
	###
	ama = am --abort
	amr = am --resolved
	ams = am --skip
	###
	b = branch
	ba = branch -a
	bd = branch -d
	bdd = branch -D
	br = branch -r
	bc = rev-parse --abbrev-ref HEAD
	bu = !git rev-parse --abbrev-ref --symbolic-full-name "@{u}"
	bs = !git-branch-status
	###
	c = commit
	ca = commit -a
	cm = commit -m
	cam = commit -am
	cem = commit --allow-empty -m
	cd = commit --amend
	cad = commit -a --amend
	ced = commit --allow-empty --amend
	###
	cl = clone
	cld = clone --depth 1
	clg = !sh -c 'git clone git://github.com/$1 $(basename $1)' -
	clgp = !sh -c 'git clone git@github.com:$1 $(basename $1)' -
	clgu = !sh -c 'git clone git@github.com:$(git config --get user.username)/$1 $1' -
	###
	cp = cherry-pick
	cpa = cherry-pick --abort
	cpc = cherry-pick --continue
	###
	d = diff
	dp = diff --patience
	dc = diff --cached
	dk = diff --check
	dck = diff --cached --check
	dt = difftool
	dct = difftool --cached
	###
	f = fetch
	fo = fetch origin
	fu = fetch upstream
	###
	fp = format-patch
	###
	fk = fsck
	###
	g = grep -p
	###
	l = log --oneline
	lg = log --oneline --graph --decorate
	###
	ls = ls-files
	lsf = !git ls-files | grep -i
	###
	m = merge
	ma = merge --abort
	mc = merge --continue
	ms = merge --skip
	###
	o = checkout
	om = checkout master
	ob = checkout -b
	opr = !sh -c 'git fo pull/$1/head:pr-$1 && git o pr-$1'
	###
	pr = prune -v
	###
	ps = push
	psf = push -f
	psu = push -u
	pst = push --tags
	###
	pso = push origin
	psao = push --all origin
	psfo = push -f origin
	psuo = push -u origin
	###
	psom = push origin master
	psaom = push --all origin master
	psfom = push -f origin master
	psuom = push -u origin master
	psoc = !git push origin $(git bc)
	psaoc = !git push --all origin $(git bc)
	psfoc = !git push -f origin $(git bc)
	psuoc = !git push -u origin $(git bc)
	psdc = !git push origin :$(git bc)
	###
	pl = pull
	pb = pull --rebase
	###
	plo = pull origin
	pbo = pull --rebase origin
	plom = pull origin master
	ploc = !git pull origin $(git bc)
	pbom = pull --rebase origin master
	pboc = !git pull --rebase origin $(git bc)
	###
	plu = pull upstream
	plum = pull upstream master
	pluc = !git pull upstream $(git bc)
	pbum = pull --rebase upstream master
	pbuc = !git pull --rebase upstream $(git bc)
	###
	rb = rebase
	rba = rebase --abort
	rbc = rebase --continue
	rbi = rebase --interactive
	rbs = rebase --skip
	###
	re = reset
	rh = reset HEAD
	reh = reset --hard
	rem = reset --mixed
	res = reset --soft
	rehh = reset --hard HEAD
	remh = reset --mixed HEAD
	resh = reset --soft HEAD
	rehom = reset --hard origin/master
	###
	r = remote
	ra = remote add
	rr = remote rm
	rv = remote -v
	rn = remote rename
	rp = remote prune
	rs = remote show
	rao = remote add origin
	rau = remote add upstream
	rro = remote remove origin
	rru = remote remove upstream
	rso = remote show origin
	rsu = remote show upstream
	rpo = remote prune origin
	rpu = remote prune upstream
	###
	rmf = rm -f
	rmrf = rm -r -f
	###
	s = status
	sb = status -s -b
	###
	sa = stash apply
	sc = stash clear
	sd = stash drop
	sl = stash list
	sp = stash pop
	ss = stash save
	ssk = stash save -k
	sw = stash show
	st = !git stash list | wc -l 2>/dev/null | grep -oEi '[0-9][0-9]*'
	###
	t = tag
	td = tag -d
	###
	w = show
	wp = show -p
	wr = show -p --no-color
	###
	svnr = svn rebase
	svnd = svn dcommit
	svnl = svn log --oneline --show-commit
	###
	subadd = !sh -c 'git submodule add git://github.com/$1 $2/$(basename $1)' -
	subrm = !sh -c 'git submodule deinit -f -- $1 && rm -rf .git/modules/$1 && git rm -f $1' -
	subup = submodule update --init --recursive
	subpull = !git submodule foreach git pull --tags origin master
	###
	assume = update-index --assume-unchanged
	unassume = update-index --no-assume-unchanged
	assumed = !git ls -v | grep ^h | cut -c 3-
	unassumeall = !git assumed | xargs git unassume
	assumeall = !git status -s | awk {'print $2'} | xargs git assume
	###
	bump = !sh -c 'git commit -am \"Version bump v$1\" && git psuoc && git release $1' -
	release = !sh -c 'git tag v$1 && git pst' -
	unrelease = !sh -c 'git tag -d v$1 && git pso :v$1' -
	merged = !sh -c 'git o master && git plom && git bd $1 && git rpo' -
	aliases = !git config -l | grep alias | cut -c 7-
	snap = !git stash save 'snapshot: $(date)' && git stash apply 'stash@{0}'
	bare = !sh -c 'git symbolic-ref HEAD refs/heads/$1 && git rm --cached -r . && git clean -xfd' -
	whois = !sh -c 'git log -i -1 --author=\"$1\" --pretty=\"format:%an <%ae>\"' -
	serve = daemon --reuseaddr --verbose --base-path=. --export-all ./.git
	###
	behind = !git rev-list --left-only --count $(git bu)...HEAD
	ahead = !git rev-list --right-only --count $(git bu)...HEAD
	###
	ours = "!f() { git checkout --ours $@ && git add $@; }; f"
	theirs = "!f() { git checkout --theirs $@ && git add $@; }; f"
	subrepo = !sh -c 'git filter-branch --prune-empty --subdirectory-filter $1 master' -
	human = name-rev --name-only --refs=refs/heads/*
[filter "lfs"]
	clean = git-lfs clean -- %f
	smudge = git-lfs smudge -- %f
	process = git-lfs filter-process
	required = true




Ejemplo .gitignore:
### Node ###

# Logs
logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Optional npm cache directory
.npm

# Dependency directories
/node_modules
/jspm_packages
/bower_components

# Yarn Integrity file
.yarn-integrity

# Optional eslint cache
.eslintcache

# dotenv environment variables file(s)
.env
.env.*

#Build generated
dist/
build/

# Serverless generated files
.serverless/

### SublimeText ###
# cache files for sublime text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache

# workspace files are user-specific
*.sublime-workspace

# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
# *.sublime-project


### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

### Vim ###
*.sw[a-p]

### WebStorm/IntelliJ ###
/.idea
modules.xml
*.ipr
*.iml


### System Files ###
*.DS_Store

# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent




npm



npm es un administrador de paquetes que le permite instalar dependencias de proyectos.



Sitio oficial: npmjs.com .



Instalación.



NPM instala con Node.js .



Además, npx se instala junto con Node.js, lo que le permite ejecutar ejecutables sin instalar: npx create-react-app my-app.



Comprobación de la instalación:



node --version | -v
npm --version | -v


Actualizar:



npm i -g npm@latest


Lista de comandos disponibles:



npm help
npm help [command-name]


Inicialización del proyecto:



npm init

// auto
npm init --yes | -y


Instalación de dependencias



npm install | i

//   
npm explore [package-name]

//   
npm doctor

// 
npm ci


Reinstalación forzosa de dependencias:



npm i --force | -f


Instalando solo paquetes de producción:



npm i --only=production | --only=prod


Agregar dependencia:



npm i [package-name]
npm i [package-name@version]

// 
npm i express


Agregar una dependencia de desarrollo:



npm i --save-dev | -D [package-name]

// 
npm i -D nodemon


Actualización de dependencia:



npm update | up [package-name]


Eliminación de dependencia:



// dependency
npm remove | rm | r [package-name]

// devDependency
npm r -D [package-name]


Paquete de instalación / actualización / desinstalación global:



npm i/up/r -g [package-name]

// 
npm i -g create-react-app
// 
create-react-app my-app


Determinación de paquetes obsoletos:



npm outdated
npm outdated [package-name]


Lista de dependencias instaladas:



npm list | ls

// top level
npm ls --depth=0 | --depth 0

// global + top level
npm ls -g --depth 0


Información del paquete:



npm view | v [package-name]

// 
npm v react
npm v react.description


Ejecución de script / ejecución de comando:



npm run [script]

// 
// package.json: "scripts": { "dev": "nodemon server.js" }
npm run dev
// script start  node server.js
npm start
npm stop


Eliminando paquetes duplicados:



npm dedupe | ddp


Eliminación de paquetes extraños:



npm prune


Detección de vulnerabilidades (amenazas a la seguridad):



npm audit
// json
npm audit --json
// plain text
npm audit --parseable


Solucione vulnerabilidades automáticamente:



npm audit fix


hilo



yarn, como npm, es un administrador de paquetes que le permite instalar dependencias del proyecto.



Sitio oficial: yarnpkg.com .



Instalación:



npm i -g yarn


El comando "yarn dlx" le permite ejecutar ejecutables sin instalar: yarn dlx create-react-app my-app. Para hacer esto, el hilo debe actualizarse a la versión 2: conjunto de hilo versión berry.



Comprobación de instalación:



yarn --version | -v


Actualizar:



yarn set version latest


Lista de comandos disponibles:



yarn help
yarn help [command-name]


Inicialización del proyecto:



yarn init

// auto
yarn init --yes | -y

// "private": true  package.json
yarn init --private | -p

// auto + private
yarn init -yp


Instalación de dependencias:



yarn
// 
yarn install

//  
yarn install --silent | -s

// 
yarn --check-files


Reinstalación forzosa de dependencias:



yarn install --force


Instalando solo paquetes de producción:



yarn install --production | --prod


Agregar dependencia:



yarn add [package-name]
yarn add [package-name@version]

// 
yarn add express

//  
yarn add --silent
// 
yarn add -s


Agregar una dependencia de desarrollo:



yarn add --dev | -D [package-name]

// 
yarn add -D nodemon


Actualización de dependencia:



yarn upgrade [package-name]


Eliminación de dependencia:



yarn remove [package-name]


Paquete de instalación / actualización / desinstalación global:



yarn global add/upgrade/remove [package-name]

// 
yarn global add create-react-app
// 
create-react-app my-app


Lista de dependencias instaladas:



yarn list

// top level
yarn list --depth=0 | --depth 0


Información del paquete:



yarn info [package-name]
// 
yarn why [package-name]

// 
yarn info react
yarn info react description
yarn why webpack


Ejecución de script / ejecución de comando:



yarn [script]
// 
yarn run [script]

// 
// package.json: "scripts": { "dev": "nodemon server.js" }
yarn dev


package.json



{
  "name": "my-app",
  "version": "1.0.0",
  "description": "my awesome app",
  "keywords": [
    "amazing",
    "awesome",
    "best"
  ],
  "private": true,
  "main": "server.js",
  "license": "MIT",
  "homepage": "https://my-website.com",
  "repository": {
    "type": "git",
    "url": "https://github.com/user/repo.git"
  },
  "repository": "github:user/repo",
  "author": {
    "name": "My Name",
    "email": "myemail@example.com",
    "url": "https://my-website.com"
  },
  "author": "My Name <myemail@example.com> (https://my-website.com)",
  "contributers": [
    {
      "name": "Friend Name",
      "email": "friendemail@example.com",
      "url": "https://friend-website.com"
    }
  ],
  "contributors": "Friend Name <friendemail.com> (https://friend-website.com)",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "dev": "nodemon server.js"
  }
}


  • name - nombre del proyecto
  • versión - versión del proyecto (ver versiones)
  • descripción - descripción del proyecto (¿por qué necesita un paquete?)
  • palabras clave: palabras clave (facilita la búsqueda en el registro de npm)
  • private — true npm
  • main —
  • repository — ( )
  • author — ( )
  • contributors — (, )
  • dependencies — (, )
  • devDependencies — (, )
  • scripts — ( , ), , , «yarn dev» «nodemon server.js»


Una lista completa de los campos disponibles en el archivo "package.json": npm-package.json



Los archivos "package-lock.json" y "yarn.lock" contienen información más completa sobre los paquetes instalados que package.json, por ejemplo, versiones de paquetes específicas en lugar de un rango versiones válidas.



Control de versiones



Cada paquete tiene una versión de tres dígitos (por ejemplo, 1.0.0), donde el primer dígito es la versión principal, el segundo es la versión secundaria y el tercero es la versión del parche (parche). El lanzamiento de una nueva versión se denomina lanzamiento.



Aumentar cada uno de estos números de acuerdo con las reglas de control de versiones semánticas (semver) significa lo siguiente:



  • mayor: realizar cambios incompatibles con la versión anterior
  • menor: nueva funcionalidad compatible con la versión anterior
  • parche: corrección de errores, mejoras menores


Los rangos de versiones o lanzamientos válidos se determinan utilizando los siguientes operadores (comparadores):



  • * - cualquier versión (igual que una cadena vacía)
  • <1.0.0: cualquier versión anterior a la 1.0.0
  • <= 1.0.0 - cualquier versión menor o igual a 1.0.0
  • > 1.0.0 - cualquier versión superior a 1.0.0
  • > = 1.0.0 - cualquier versión mayor o igual a 1.0.0
  • = 1.0.0 - solo versión 1.0.0 (el operador "=" se puede omitir)
  • > = 1.0.0 <2.0.0 - mayor o igual que 1.0.0 y menor que 2.0.0
  • 1.0.0-2.0.0 - un conjunto de versiones inclusive
  • ^ 1.0.0 - versiones menores y de parche (> = 1.0.0 <2.0.0)
  • ~ .1.0.0 - solo versiones de parches (> = 1.0.0 <1.1.0)


Detalles para semver: node-semver .



Gracias por su atención.



All Articles