15
AUTHORS.md
15
AUTHORS.md
@ -14,7 +14,7 @@ Contributors are listed in alphabetical order by GitHub login.
|
|||||||
* [Bryce J. (bj1)](https://github.com/bj1) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=bj1)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Abj1)
|
* [Bryce J. (bj1)](https://github.com/bj1) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=bj1)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Abj1)
|
||||||
* [Arturo Fernandez (bsnux)](https://github.com/bsnux) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=bsnux)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Absnux)
|
* [Arturo Fernandez (bsnux)](https://github.com/bsnux) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=bsnux)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Absnux)
|
||||||
* [Alex Cabrera (cabreraalex)](https://github.com/cabreraalex) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=cabreraalex)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Acabreraalex)
|
* [Alex Cabrera (cabreraalex)](https://github.com/cabreraalex) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=cabreraalex)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Acabreraalex)
|
||||||
* [Carlos Mantilla (ceoaliongroo)](https://github.com/ceoaliongroo) — [17+](https://github.com/jlevy/the-art-of-command-line/commits?author=ceoaliongroo)/[11+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aceoaliongroo) — _translator and maintainer (es)_
|
* [Carlos Mantilla (ceoaliongroo)](https://github.com/ceoaliongroo) — [21+](https://github.com/jlevy/the-art-of-command-line/commits?author=ceoaliongroo)/[12+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aceoaliongroo) — _translator and maintainer (es)_
|
||||||
* [Chris Kuehl (chriskuehl)](https://github.com/chriskuehl) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=chriskuehl)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Achriskuehl)
|
* [Chris Kuehl (chriskuehl)](https://github.com/chriskuehl) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=chriskuehl)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Achriskuehl)
|
||||||
* [Corey "See More" Richardson (cmr)](https://github.com/cmr) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=cmr)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Acmr)
|
* [Corey "See More" Richardson (cmr)](https://github.com/cmr) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=cmr)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Acmr)
|
||||||
* [Colas BROUX (ColasBroux)](https://github.com/ColasBroux) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=ColasBroux)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AColasBroux)
|
* [Colas BROUX (ColasBroux)](https://github.com/ColasBroux) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=ColasBroux)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AColasBroux)
|
||||||
@ -24,8 +24,9 @@ Contributors are listed in alphabetical order by GitHub login.
|
|||||||
* [Dmytro Danylevskyi (danylevskyi)](https://github.com/danylevskyi) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=danylevskyi)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adanylevskyi)
|
* [Dmytro Danylevskyi (danylevskyi)](https://github.com/danylevskyi) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=danylevskyi)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adanylevskyi)
|
||||||
* [Dave Loyall (daveloyall)](https://github.com/daveloyall) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=daveloyall)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adaveloyall)
|
* [Dave Loyall (daveloyall)](https://github.com/daveloyall) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=daveloyall)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adaveloyall)
|
||||||
* [Deborah Digges (Deborah-Digges)](https://github.com/Deborah-Digges) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=Deborah-Digges)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ADeborah-Digges)
|
* [Deborah Digges (Deborah-Digges)](https://github.com/Deborah-Digges) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=Deborah-Digges)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ADeborah-Digges)
|
||||||
* [James Luck (delucks)](https://github.com/delucks) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=delucks)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adelucks)
|
* [Jamie Luck (delucks)](https://github.com/delucks) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=delucks)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adelucks)
|
||||||
* [Dima Paloskin (dimapaloskin)](https://github.com/dimapaloskin) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=dimapaloskin)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adimapaloskin)
|
* [Dima Paloskin (dimapaloskin)](https://github.com/dimapaloskin) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=dimapaloskin)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adimapaloskin)
|
||||||
|
* [Michael Diamond (dimo414)](https://github.com/dimo414) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=dimo414)/[4+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adimo414)
|
||||||
* [doublemarket (doublemarket)](https://github.com/doublemarket) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=doublemarket)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adoublemarket) — _translator and maintainer (ja)_
|
* [doublemarket (doublemarket)](https://github.com/doublemarket) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=doublemarket)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Adoublemarket) — _translator and maintainer (ja)_
|
||||||
* [Vincent Wong (EaterOA)](https://github.com/EaterOA) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=EaterOA)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AEaterOA)
|
* [Vincent Wong (EaterOA)](https://github.com/EaterOA) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=EaterOA)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AEaterOA)
|
||||||
* [Fazle Arefin (fazlearefin)](https://github.com/fazlearefin) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=fazlearefin)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Afazlearefin)
|
* [Fazle Arefin (fazlearefin)](https://github.com/fazlearefin) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=fazlearefin)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Afazlearefin)
|
||||||
@ -35,9 +36,9 @@ Contributors are listed in alphabetical order by GitHub login.
|
|||||||
* [Beau Hastings (hastinbe)](https://github.com/hastinbe) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=hastinbe)/[4+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ahastinbe)
|
* [Beau Hastings (hastinbe)](https://github.com/hastinbe) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=hastinbe)/[4+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ahastinbe)
|
||||||
* [Sung Kim (hunkim)](https://github.com/hunkim) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=hunkim)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ahunkim) — _translator (ko)_
|
* [Sung Kim (hunkim)](https://github.com/hunkim) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=hunkim)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ahunkim) — _translator (ko)_
|
||||||
* [Hunter-Github](https://github.com/Hunter-Github) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=Hunter-Github)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AHunter-Github)
|
* [Hunter-Github](https://github.com/Hunter-Github) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=Hunter-Github)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AHunter-Github)
|
||||||
* [Ivgeni Segal (isegal)](https://github.com/isegal) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=isegal)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aisegal)
|
* [Ivgeni "Iv" Segal (isegal)](https://github.com/isegal) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=isegal)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aisegal)
|
||||||
* [Alan Brogan (jalanb)](https://github.com/jalanb) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=jalanb)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajalanb)
|
* [Alan Brogan (jalanb)](https://github.com/jalanb) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=jalanb)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajalanb)
|
||||||
* [Joshua Levy (jlevy)](https://github.com/jlevy) — [102+](https://github.com/jlevy/the-art-of-command-line/commits?author=jlevy)/[19+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajlevy) — _original author and maintainer_
|
* [Joshua Levy (jlevy)](https://github.com/jlevy) — [109+](https://github.com/jlevy/the-art-of-command-line/commits?author=jlevy)/[19+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajlevy) — _original author and maintainer_
|
||||||
* [Jesse Sightler (jsight)](https://github.com/jsight) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=jsight)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajsight)
|
* [Jesse Sightler (jsight)](https://github.com/jsight) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=jsight)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajsight)
|
||||||
* [Konstantin Mikhaylov (jtraub)](https://github.com/jtraub) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=jtraub)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajtraub)
|
* [Konstantin Mikhaylov (jtraub)](https://github.com/jtraub) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=jtraub)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ajtraub)
|
||||||
* [Wael M. Nasreddine (kalbasit)](https://github.com/kalbasit) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=kalbasit)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Akalbasit)
|
* [Wael M. Nasreddine (kalbasit)](https://github.com/kalbasit) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=kalbasit)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Akalbasit)
|
||||||
@ -55,8 +56,9 @@ Contributors are listed in alphabetical order by GitHub login.
|
|||||||
* [Oleg Berman (olegberman)](https://github.com/olegberman) — [15+](https://github.com/jlevy/the-art-of-command-line/commits?author=olegberman)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aolegberman) — _translator and maintainer (ru)_
|
* [Oleg Berman (olegberman)](https://github.com/olegberman) — [15+](https://github.com/jlevy/the-art-of-command-line/commits?author=olegberman)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aolegberman) — _translator and maintainer (ru)_
|
||||||
* [osmero](https://github.com/osmero) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=osmero)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aosmero) — _translator (ru)_
|
* [osmero](https://github.com/osmero) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=osmero)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aosmero) — _translator (ru)_
|
||||||
* [Serg Petrov (p12se)](https://github.com/p12se) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=p12se)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ap12se)
|
* [Serg Petrov (p12se)](https://github.com/p12se) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=p12se)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ap12se)
|
||||||
* [Peter Kokot (peterkokot)](https://github.com/peterkokot) — [25+](https://github.com/jlevy/the-art-of-command-line/commits?author=peterkokot)/[18+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Apeterkokot) — _translator and maintainer (sl)_
|
* [Peter Kokot (peterkokot)](https://github.com/peterkokot) — [29+](https://github.com/jlevy/the-art-of-command-line/commits?author=peterkokot)/[20+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Apeterkokot) — _translator and maintainer (sl)_
|
||||||
* [曾楚杰 (Psycho7)](https://github.com/Psycho7) — [16+](https://github.com/jlevy/the-art-of-command-line/commits?author=Psycho7)/[7+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3APsycho7) — _translator and maintainer (zh)_
|
* [曾楚杰 (Psycho7)](https://github.com/Psycho7) — [19+](https://github.com/jlevy/the-art-of-command-line/commits?author=Psycho7)/[8+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3APsycho7) — _translator and maintainer (zh)_
|
||||||
|
* [Rahul Kavale (rahulkavale)](https://github.com/rahulkavale) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=rahulkavale)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Arahulkavale)
|
||||||
* [Raju Devidas Vindane (rajuvindane)](https://github.com/rajuvindane) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=rajuvindane)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Arajuvindane)
|
* [Raju Devidas Vindane (rajuvindane)](https://github.com/rajuvindane) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=rajuvindane)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Arajuvindane)
|
||||||
* [Rasmus Wriedt Larsen (RasmusWL)](https://github.com/RasmusWL) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=RasmusWL)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ARasmusWL)
|
* [Rasmus Wriedt Larsen (RasmusWL)](https://github.com/RasmusWL) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=RasmusWL)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ARasmusWL)
|
||||||
* [Saksham Sharma (saksham0808)](https://github.com/saksham0808) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=saksham0808)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Asaksham0808)
|
* [Saksham Sharma (saksham0808)](https://github.com/saksham0808) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=saksham0808)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Asaksham0808)
|
||||||
@ -65,6 +67,7 @@ Contributors are listed in alphabetical order by GitHub login.
|
|||||||
* [Snowcat8436 (Snowcat8436)](https://github.com/Snowcat8436) — [4+](https://github.com/jlevy/the-art-of-command-line/commits?author=Snowcat8436)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ASnowcat8436) — _translator (ko)_
|
* [Snowcat8436 (Snowcat8436)](https://github.com/Snowcat8436) — [4+](https://github.com/jlevy/the-art-of-command-line/commits?author=Snowcat8436)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ASnowcat8436) — _translator (ko)_
|
||||||
* [Soham Chakraborty (SohamChakraborty)](https://github.com/SohamChakraborty) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=SohamChakraborty)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ASohamChakraborty)
|
* [Soham Chakraborty (SohamChakraborty)](https://github.com/SohamChakraborty) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=SohamChakraborty)/[3+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3ASohamChakraborty)
|
||||||
* [spmbt (spmbt)](https://github.com/spmbt) — [13+](https://github.com/jlevy/the-art-of-command-line/commits?author=spmbt)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aspmbt) — _translator (ru)_
|
* [spmbt (spmbt)](https://github.com/spmbt) — [13+](https://github.com/jlevy/the-art-of-command-line/commits?author=spmbt)/[0+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Aspmbt) — _translator (ru)_
|
||||||
|
* [Stepan Babala (stepan0904)](https://github.com/stepan0904) — [27+](https://github.com/jlevy/the-art-of-command-line/commits?author=stepan0904)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Astepan0904) — _translator and maintaner (uk)_
|
||||||
* [Steven Liu (stevenlordiam)](https://github.com/stevenlordiam) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=stevenlordiam)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Astevenlordiam) — _translator (zh)_
|
* [Steven Liu (stevenlordiam)](https://github.com/stevenlordiam) — [2+](https://github.com/jlevy/the-art-of-command-line/commits?author=stevenlordiam)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Astevenlordiam) — _translator (zh)_
|
||||||
* [Fabien Dubosson (StreakyCobra)](https://github.com/StreakyCobra) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=StreakyCobra)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AStreakyCobra)
|
* [Fabien Dubosson (StreakyCobra)](https://github.com/StreakyCobra) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=StreakyCobra)/[1+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3AStreakyCobra)
|
||||||
* [taxusyew](https://github.com/taxusyew) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=taxusyew)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ataxusyew)
|
* [taxusyew](https://github.com/taxusyew) — [1+](https://github.com/jlevy/the-art-of-command-line/commits?author=taxusyew)/[2+](https://github.com/jlevy/the-art-of-command-line/issues?q=author%3Ataxusyew)
|
||||||
|
90
README-es.md
90
README-es.md
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -21,13 +21,14 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
La fluidez en el terminal es una destreza a menudo abandonada y considerada arcaica, pero esta mejora su flexibilidad y productividad como ingeniero en formas obvia y sutil. Esta es una selección de notas y consejos al usar el terminal que encontré útiles al trabajar en Linux. Algunos consejos son elementales y algunos bastante específicos, sofisticados u oscuros. Esta página no es larga, pero si puedes usar y recordar todos los puntos aquí mostrados, sabrás un montón.
|
La fluidez en el terminal es una destreza a menudo abandonada y considerada arcaica, pero esta mejora su flexibilidad y productividad como ingeniero en formas obvia y sutil. Esta es una selección de notas y consejos al usar el terminal que encontramos útiles al trabajar en Linux. Algunos consejos son elementales y algunos bastante específicos, sofisticados u oscuros. Esta página no es larga, pero si puedes usar y recordar todos los puntos aquí mostrados, sabrás un montón.
|
||||||
|
|
||||||
|
Este trabajo es el resultado de [muchos autores y traductores](AUTHORS.md).
|
||||||
La mayor parte
|
La mayor parte
|
||||||
[originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands)
|
[originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands)
|
||||||
[apareció](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix)
|
[apareció](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix)
|
||||||
en [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),
|
en [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),
|
||||||
pero debido al interés mostrado, parece que vale la pena usar Github, donde existen personas más talentosas que fácilmente pueden sugerir mejoras. Si ve un error o algo que podría ser mejor, por favor, crea un issue o PR! (Por supuesto primero revisa la sección meta de PRs/issues.)
|
pero debido al interés mostrado, parecía valer la pena usar Github, donde personas más talentosas que el author original pudiendo fácilmente sugerir mejoras. Si ve un error o algo que podría ser mejor, por favor, crea un issue o PR! (Por supuesto primero revisa la sección meta de PRs/issues.)
|
||||||
|
|
||||||
|
|
||||||
## Meta
|
## Meta
|
||||||
@ -55,13 +56,13 @@ Notas:
|
|||||||
|
|
||||||
- Aprende sobre redirección de salida `>`, entrada `<` y pipes utilizando `|`. Conozca que `>` sobrescribe el archivo de salida y `>>` añade. Aprende sobre stdout y stderr.
|
- Aprende sobre redirección de salida `>`, entrada `<` y pipes utilizando `|`. Conozca que `>` sobrescribe el archivo de salida y `>>` añade. Aprende sobre stdout y stderr.
|
||||||
|
|
||||||
- Aprende sobre expansión de archivos glob con `*` (y tal vez `?` y `{`...`}`) y quoting y la diferencia entre comillas dobles `"` y simples `'`. (Ver más en expansión de variables más abajo.)
|
- Aprende sobre expansión de archivos glob con `*` (y tal vez `?` y `[`...`]`) y quoting y la diferencia entre comillas dobles `"` y simples `'`. (Ver más en expansión de variables más abajo.)
|
||||||
|
|
||||||
- Familiarízate con la administración de trabajo en Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc.
|
- Familiarízate con la administración de trabajo en Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc.
|
||||||
|
|
||||||
- Conoce `ssh` y lo básico de autenticación sin contraseña, vía `ssh-agent`, `ssh-add`, etc.
|
- Conoce `ssh` y lo básico de autenticación sin contraseña, vía `ssh-agent`, `ssh-add`, etc.
|
||||||
|
|
||||||
- Administración de archivos básica: `ls` y `ls -l` (en particular, aprende el significado de cada columna en `ls -l`), `less`, `head`, `tail` y `tail -f` (o incluso mejor, `less +F`), `ln` y `ln -s` (aprende las diferencias y ventajas entre enlaces hard y soft), `chown`, `chmod`, `du` (para un resumen rápido del uso del disco: `du -hs *`). Para administración de archivos de sistema, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`.
|
- Administración de archivos básica: `ls` y `ls -l` (en particular, aprende el significado de cada columna en `ls -l`), `less`, `head`, `tail` y `tail -f` (o incluso mejor, `less +F`), `ln` y `ln -s` (aprende las diferencias y ventajas entre enlaces hard y soft), `chown`, `chmod`, `du` (para un resumen rápido del uso del disco: `du -hs *`). Para administración de archivos de sistema, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. Aprenda que un inode es `ls -i` or `df -i`).
|
||||||
|
|
||||||
- Administración básica de redes: `ip` o `ifconfig`, `dig`.
|
- Administración básica de redes: `ip` o `ifconfig`, `dig`.
|
||||||
|
|
||||||
@ -72,11 +73,13 @@ Notas:
|
|||||||
|
|
||||||
## De uso diario
|
## De uso diario
|
||||||
|
|
||||||
- En Bash, se usa **Tab** para completar los argumentos y **ctrl-r** para buscar a través del historial de comandos.
|
- En Bash, se usa **Tab** para completar los argumentos o lista todos los comandos disponibles y **ctrl-r** para buscar a través del historial de comandos (despues de presionar, escribe la búsqueda, presiona **ctrl-r** repetidamente para hacer un ciclo a través de más coincidencias, presiona **Enter** para ejecurar el comando encontrado, o presiona la flecha derecha para poner el resultado en la línea actual y editar).
|
||||||
|
|
||||||
- En Bash, se usa **ctrl-w** para borrar la última palabra, y **ctrl-u** para borrar todo hacia atrás hasta el inicio de la línea. Se usa **alt-b** y **alt-f** para moverse entre palabras, **ctrl-a** para mover el cursor al principio de la línea, **ctrl-e** para mover el cursor al final de la línea, **ctrl-k** para eliminar hasta el final de la línea, **ctrl-l** para limpiar la pantalla. Ver `man readline` para todos los atajos de teclado por defecto en Bash. Son una gran cantidad. Por ejemplo **alt-.** realiza un ciclo a través de los comandos previos, y **alt-*** expande un glob.
|
- En Bash, se usa **ctrl-w** para borrar la última palabra, y **ctrl-u** para borrar todo hacia atrás hasta el inicio de la línea. Se usa **alt-b** y **alt-f** para moverse entre palabras, **ctrl-a** para mover el cursor al principio de la línea, **ctrl-e** para mover el cursor al final de la línea, **ctrl-k** para eliminar hasta el final de la línea, **ctrl-l** para limpiar la pantalla. Ver `man readline` para todos los atajos de teclado por defecto en Bash. Son una gran cantidad. Por ejemplo **alt-.** realiza un ciclo a través de los comandos previos, y **alt-*** expande un glob.
|
||||||
|
|
||||||
- Alternativamente, si amas los atajos de teclado vi-style, usa `set -o vi`.
|
- Alternativamente, si amas los atajos de teclado vi-style, usa `set -o vi`. (y `set -o emacs` para regresar a la anterior).
|
||||||
|
|
||||||
|
- Para editar largos comandos, después de configurar to editor (por ejemplo `export EDITOR=vim`), **ctrl-x** **ctrl-e** se abrirá el comando actual en un editor para editar multiples líneas. O en estilo vi, **escape-v**.
|
||||||
|
|
||||||
- Para ver los últimos comandos, `history`. También existen abreviaciones, tales como, `!$` (último argumento) y `!!` último comando, aunque son fácilmente remplazados con **ctrl-r** y **alt-.**.
|
- Para ver los últimos comandos, `history`. También existen abreviaciones, tales como, `!$` (último argumento) y `!!` último comando, aunque son fácilmente remplazados con **ctrl-r** y **alt-.**.
|
||||||
|
|
||||||
@ -106,7 +109,11 @@ Notas:
|
|||||||
|
|
||||||
- Usa `alias` para crear atajos para comandos comúnmente usados. Por ejemplo, `alias ll="las -latr"` crea el alias `ll`
|
- Usa `alias` para crear atajos para comandos comúnmente usados. Por ejemplo, `alias ll="las -latr"` crea el alias `ll`
|
||||||
|
|
||||||
- En Bash scripts, usa `set -x` para depurar la salida. Usa el modo estricto cuando se posible. Usa `set -e` para abortar en caso de errores. Usa `set -o pipefail` también, para ser estrictos sobre los errores (aunque este tema es un poco delicado). Para scripts más complejos, usa también `trap`.
|
- En Bash scripts, usa `set -x` (o su variantes `set -v`, que registra las entradas sin procesar, incluyendo variables sin expander y comantarios) para depurar la salida. Usa el modo estricto al menos que tengas una buena razón para no hacerlo: Usa `set -e` para abortar en caso de errores (códigos de salida distintos a cero). Usa `set -u` para detectar uso de variables no definidas. Considera `set -o pipefail` también, para los errores con pipes, también (estudiar mas sobre este como un tema delicado). Para scripts más complejos, usa también `trap`. en EXIT o ERR. Un hábito útil es para comenzar un script como este, el cual detectará y abortará con errores comunes e imprimirá un mensaje:
|
||||||
|
```bash
|
||||||
|
set -euo pipefail
|
||||||
|
trap "echo 'error: Falló del Script: ver arriba comando que falló'" ERR
|
||||||
|
```
|
||||||
|
|
||||||
- En Bash scripts, subshells (escritos con paréntesis) son maneras convenientes para agrupar los comandos. Un ejemplo común es temporalmente moverse hacia un directorio de trabajo diferente, Ej.
|
- En Bash scripts, subshells (escritos con paréntesis) son maneras convenientes para agrupar los comandos. Un ejemplo común es temporalmente moverse hacia un directorio de trabajo diferente, Ej.
|
||||||
```bash
|
```bash
|
||||||
@ -117,6 +124,8 @@ Notas:
|
|||||||
|
|
||||||
- En Bash, considera que hay muchas formas de expansión de variables. Verificar la existencia de una variable: `${name:?error message}`. Por ejemplo, si un script Bash requiere un único argumento, solo escribe `input_file=${1:?usage: $0 input_file}`. Expansión aritmética: `i=$(( (i + 1) % 5 ))`. Secuencias: `{1..10}`. Reducción de cadenas de texto: `${var%suffix}` y `${var#prefix}`. Por ejemplo si `var=foo.pdf`, entonces `echo ${var%.pdf}.txt` imprime `foo.txt`.
|
- En Bash, considera que hay muchas formas de expansión de variables. Verificar la existencia de una variable: `${name:?error message}`. Por ejemplo, si un script Bash requiere un único argumento, solo escribe `input_file=${1:?usage: $0 input_file}`. Expansión aritmética: `i=$(( (i + 1) % 5 ))`. Secuencias: `{1..10}`. Reducción de cadenas de texto: `${var%suffix}` y `${var#prefix}`. Por ejemplo si `var=foo.pdf`, entonces `echo ${var%.pdf}.txt` imprime `foo.txt`.
|
||||||
|
|
||||||
|
- Utilizando la expansión de corchetes `{`...`}` puede reducir el tener que retipear un texto similar y automatizar conbinaciones de elementos. Esto es útil en ejemplos como `mv foo.{txt,pdf} some-dir` (el cual mueve ambos archivos), `cp somefile{,.bak}` (el cual se expandirá a `cp somefile somefile.bak`) o `mkdir -p test-{a,b,c}/subtest-{1,2,3}` (el cual se expandirá en todas las posibles conbinaciones y creará un árbol de directorios).
|
||||||
|
|
||||||
- La salida de un comando puede ser tratado como un archivo por medio de `<(some command)`. Por ejemplo, comparar el `/etc/hosts` local con uno remoto:
|
- La salida de un comando puede ser tratado como un archivo por medio de `<(some command)`. Por ejemplo, comparar el `/etc/hosts` local con uno remoto:
|
||||||
```sh
|
```sh
|
||||||
diff /etc/hosts <(ssh somehost cat /etc/hosts)
|
diff /etc/hosts <(ssh somehost cat /etc/hosts)
|
||||||
@ -124,11 +133,11 @@ Notas:
|
|||||||
|
|
||||||
- Conocer acerca de "here documents" en Bash, como también de `cat <<EOF ...`.
|
- Conocer acerca de "here documents" en Bash, como también de `cat <<EOF ...`.
|
||||||
|
|
||||||
- En Bash, redirecciona ambas la salida estándar y el error estándar, mediante: `some-command >logfile 2>&1`. Frecuentemente, para garantizar que un comando no haya dejado abierto un archivo para controlar la entrada estándar vinculada al terminal en el que te encuentras y también como buena práctica puedes agregar `</dev/null`.
|
- En Bash, redirecciona ambas la salida estándar y el error estándar, mediante: `some-command >logfile 2>&1` o `some-command &>logfile`. Frecuentemente, para garantizar que un comando no haya dejado abierto un archivo para controlar la entrada estándar vinculada al terminal en el que te encuentras y también como buena práctica puedes agregar `</dev/null`.
|
||||||
|
|
||||||
- Usa `man ascii` para una buena tabla ASCII con valores hexadecimal y decimales. Para información de codificación general, `man unicode`, `man utf-8`, y `man latin1` son de utilidad.
|
- Usa `man ascii` para una buena tabla ASCII con valores hexadecimal y decimales. Para información de codificación general, `man unicode`, `man utf-8`, y `man latin1` son de utilidad.
|
||||||
|
|
||||||
- Usa `screen` o [`tmux`](https://tmux.github.io/) para multiplexar la pantalla, especialmente útil en sesiones ssh remotas y para desconectar y reconectar a una sesión. Una alternativa más minimalista para persistencia de la sesión solo sería `dtach`.
|
- Usa `screen` o [`tmux`](https://tmux.github.io/) para multiplexar la pantalla, especialmente útil en sesiones ssh remotas y para desconectar y reconectar a una sesión. `byobu` puede mejorar la pantalla o tmux proporcionando mayor información y gestión ás sencilla. Una alternativa más minimalista para persistencia de la sesión solo sería `dtach`.
|
||||||
|
|
||||||
- En ssh, saber cómo hacer un port tunnel con `-L` o `-D` (y de vez en cuando `-R`) es útil, Ej. para acceder a sitios web desde un servidor remoto.
|
- En ssh, saber cómo hacer un port tunnel con `-L` o `-D` (y de vez en cuando `-R`) es útil, Ej. para acceder a sitios web desde un servidor remoto.
|
||||||
|
|
||||||
@ -145,6 +154,8 @@ Notas:
|
|||||||
|
|
||||||
- Algunas otras opciones relevantes a ssh son sensibles en cuanto a seguridad y deben ser usadas con cuidado, Ej. por subnet, host o en redes confiables: `StrictHostKeyChecking=no`, `ForwardAgent=yes`.
|
- Algunas otras opciones relevantes a ssh son sensibles en cuanto a seguridad y deben ser usadas con cuidado, Ej. por subnet, host o en redes confiables: `StrictHostKeyChecking=no`, `ForwardAgent=yes`.
|
||||||
|
|
||||||
|
- Considera [`mosh`](https://mosh.mit.edu/) una alternativa para ssh que utiliza UDP, evitando conexiones caidas y agregando conveniencia en el camino. (require configuración del lado del servidor).
|
||||||
|
|
||||||
- Para obtener permiso sobre un archivo en forma octal, el cual es útil para la configuración del sistema pero no está disponible con `ls` y fácil de estropear, usa algo como
|
- Para obtener permiso sobre un archivo en forma octal, el cual es útil para la configuración del sistema pero no está disponible con `ls` y fácil de estropear, usa algo como
|
||||||
```sh
|
```sh
|
||||||
stat -c '%A %a %n' /etc/timezone
|
stat -c '%A %a %n' /etc/timezone
|
||||||
@ -174,9 +185,11 @@ Notas:
|
|||||||
|
|
||||||
- Para JSON usa [`jq`](http://stedolan.github.io/jq/).
|
- Para JSON usa [`jq`](http://stedolan.github.io/jq/).
|
||||||
|
|
||||||
|
- Para YAML, usa [`shyaml`](https://github.com/0k/shyaml).
|
||||||
|
|
||||||
- Para archivos Excel o CSV, [csvkit](https://github.com/onyxfish/csvkit) proporciona `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc.
|
- Para archivos Excel o CSV, [csvkit](https://github.com/onyxfish/csvkit) proporciona `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc.
|
||||||
|
|
||||||
- Para Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) es conveniente y [`s4cmd`](https://github.com/bloomreach/s4cmd) es el mas rápido. [`aws`](https://github.com/aws/aws-cli) de Amazon es esencial para otras tareas relacionadas al AWS.
|
- Para Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) es conveniente y [`s4cmd`](https://github.com/bloomreach/s4cmd) es el mas rápido. [`aws`](https://github.com/aws/aws-cli) de Amazon y el mejorado [`saws`](https://github.com/donnemartin/saws) son esenciales para otras tareas relacionadas al AWS.
|
||||||
|
|
||||||
- Conoce acerca de `sort` y `uniq`, incluyendo las opciones de uniq `-u` y `-d` -- ver [one-liners](https://github.com/jlevy/the-art-of-command-line/blob/master/README-es.md#one-liners) más abajo. Ver también `comm`
|
- Conoce acerca de `sort` y `uniq`, incluyendo las opciones de uniq `-u` y `-d` -- ver [one-liners](https://github.com/jlevy/the-art-of-command-line/blob/master/README-es.md#one-liners) más abajo. Ver también `comm`
|
||||||
|
|
||||||
@ -195,12 +208,19 @@ Notas:
|
|||||||
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
- Para renombrar varios archivos a la vez de acuerdo a un patrón, usa `rename`. Para renombramientos complejos, [`repren`](https://github.com/jlevy/repren) puede ayudar.
|
- Para renombrar multiples y/o buscar y remplazar dentro de archivos, intenta [`repren`](https://github.com/jlevy/repren). (En algunos casos el comando `rename` también permite multiples renombramientos, pero sea cuidadoso ya que esta funcionalidad no es igual en todas las distribuciones de Linux.)
|
||||||
```sh
|
```sh
|
||||||
# Recuperar archivos de respaldo foo.bak -> foo:
|
|
||||||
rename 's/\.bak$//' *.bak
|
|
||||||
# Renombramiento completo de archivos, carpetas y contenidos foo -> bar:
|
# Renombramiento completo de archivos, carpetas y contenidos foo -> bar:
|
||||||
repren --full --preserve-case --from foo --to bar .
|
repren --full --preserve-case --from foo --to bar .
|
||||||
|
# Recuperar archivos de respaldo cualquier.bak -> cualquier:
|
||||||
|
repren --renames --from '.*)\.bak' --to '\1' *.bak
|
||||||
|
# Igual que arriba, utilizando rename, si esta disponible:
|
||||||
|
rename 's/\.bak$//' *.bak
|
||||||
|
```
|
||||||
|
|
||||||
|
- Como dice la página de man, `rsync` es una muy rápida y extraordinariamente versatil herramienta de copiado. Esta se conoce por la sincronización entre máquinas pero es igualmente útil localmente. Esta también se encuentra entre las [formas más rápidas](https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html) para borrar un gran número de archivos:
|
||||||
|
```sh
|
||||||
|
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
|
||||||
```
|
```
|
||||||
|
|
||||||
- Usa `shuf` para mezclar o seleccionar líneas aleatorias de un archivo.
|
- Usa `shuf` para mezclar o seleccionar líneas aleatorias de un archivo.
|
||||||
@ -209,9 +229,9 @@ Notas:
|
|||||||
|
|
||||||
- Si alguna vez necesitas escribir un tab literal en una línea de comandos en Bash (Ej. para el argumento -t de ordenar), presiona **ctrl-v** **[Tab]** o escribe `$'\t'` (El último es mejor porque puedes copiarlo/pegarlo).
|
- Si alguna vez necesitas escribir un tab literal en una línea de comandos en Bash (Ej. para el argumento -t de ordenar), presiona **ctrl-v** **[Tab]** o escribe `$'\t'` (El último es mejor porque puedes copiarlo/pegarlo).
|
||||||
|
|
||||||
- Las herramientas estándar para reparar el código fuente son `diff` y `patch`. Consulta también `diffstat` para resumen estadístico de una diff. Considera `diff -r` trabaja con directorios por completo. Usa `diff -r tree1 tree2 | diffstat` para el resumen de cambios.
|
- Las herramientas estándar para reparar el código fuente son `diff` y `patch`. Consulta también `diffstat` para resumen estadístico de una diff y `sdiff` para un diff puesto lado a lado. Considera `diff -r` trabaja con directorios por completo. Usa `diff -r tree1 tree2 | diffstat` para el resumen de cambios. Urilizá `vimdiff` para comparar y editar archivos.
|
||||||
|
|
||||||
- Para archivos binarios, usa `hd` para volcados hexdecimales simples y `bvi` para edición de binario.
|
- Para archivos binarios, usa `hd`, `hexdeump` or `xxd` para volcados hexdecimales simples y `bvi` o `biew` para edición de binario.
|
||||||
|
|
||||||
- También para archivos binarios, `strings` (además de `grep`, etc.) permite encontrar fragmentos de texto.
|
- También para archivos binarios, `strings` (además de `grep`, etc.) permite encontrar fragmentos de texto.
|
||||||
|
|
||||||
@ -224,16 +244,20 @@ Notas:
|
|||||||
|
|
||||||
- Para dividir archivos en múltiples partes, consulta `split` (para dividir por tamaño) y `csplit` (para dividir por un patrón).
|
- Para dividir archivos en múltiples partes, consulta `split` (para dividir por tamaño) y `csplit` (para dividir por un patrón).
|
||||||
|
|
||||||
|
- Para manipular expresiones de fecha y tiempo, usa `dateadd`, `datediff`, `strptime` etc. de [`dateutils`](http://www.fresse.org/dateutils/).
|
||||||
|
|
||||||
- Usa `zless`, `zmore`, `zcat`, y `zgrep` para operar sobre archivos comprimidos.
|
- Usa `zless`, `zmore`, `zcat`, y `zgrep` para operar sobre archivos comprimidos.
|
||||||
|
|
||||||
|
|
||||||
## Depuración del sistema
|
## Depuración del sistema
|
||||||
|
|
||||||
- Para depuración web, `curl` y `curl -I` son prácticos, o como sus equivalentes `wget`, o el más moderno [`httpie`](https://github.com/jakubroztocil/httpie).
|
- Para depuración web, `curl` y `curl -I` son prácticos, o como sus equivalentes `wget`, o el más moderno [`httpie`](https://github.com/jkbrzt/httpie).
|
||||||
|
|
||||||
- Para conocer el estado del disco/cpu/red, usa `iostat`, `netstat`, `top` (o el mejor `htop`), y (especialmente) `dstat`. Bueno para recibir una idea rápida de qué está pasando con un sistema.
|
- Para conocer el estado del cpu/disco, las clásicas herramientas son `top` (o mejor `htop`), `iostat`, y `iotop`. Usa `iostat -mxz 15` para CPU básicas y estadísticas detalladas y visión de rendimiento por partición del disco.
|
||||||
|
|
||||||
- Para una visión general en mayor profundidad, usa [`glances`](https://github.com/nicolargo/glances). Este se presenta con varios niveles de estadística en un solo terminal. Muy útil para una verificación rápida de varios subsistemas.
|
- Para detalles de la conexión de red, usa `netstat` y `ss`.
|
||||||
|
|
||||||
|
- Para una rápida visión general de que esta pasando en un sistema, `dstat` es especialmente útil. Para una visión general más amplia con detalles usa [`glances`](https://github.com/nicolargo/glances).
|
||||||
|
|
||||||
- Para conocer el estado de la memoria, ejecuta y entiende la salida de `free` y `vmstat`. En particular, ten en cuenta que el valor "cached" es mantenido en memoria por el kernel de Linux como un archivo de cache, por lo que efectivamente cuenta como valor para "free".
|
- Para conocer el estado de la memoria, ejecuta y entiende la salida de `free` y `vmstat`. En particular, ten en cuenta que el valor "cached" es mantenido en memoria por el kernel de Linux como un archivo de cache, por lo que efectivamente cuenta como valor para "free".
|
||||||
|
|
||||||
@ -259,7 +283,7 @@ Notas:
|
|||||||
|
|
||||||
- Cuando se depura porque algo salió mal en el pasado, `sar` puede ser muy útil. Este muestra la estadística histórica en CPU, memoria, red, etc.
|
- Cuando se depura porque algo salió mal en el pasado, `sar` puede ser muy útil. Este muestra la estadística histórica en CPU, memoria, red, etc.
|
||||||
|
|
||||||
- Para sistemas y análisis de rendimiento de mayor profundidad, examina `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), y [`sysdig`](https://github.com/draios/sysdig).
|
- Para sistemas y análisis de rendimiento de mayor profundidad, examina `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](https://en.wikipedia.org/wiki/Perf_(Linux)), y [`sysdig`](https://github.com/draios/sysdig).
|
||||||
|
|
||||||
- Comprueba en que OS se encuentra con `uname` o `uname -a` (información general en Unix/kernel) o `lsb_release -a` (información en Linux distro).
|
- Comprueba en que OS se encuentra con `uname` o `uname -a` (información general en Unix/kernel) o `lsb_release -a` (información en Linux distro).
|
||||||
|
|
||||||
@ -277,7 +301,7 @@ Algunos ejemplos de comandos reunidos:
|
|||||||
cat a b b | sort | uniq -u > c # c es el conjunto diferencia a - b
|
cat a b b | sort | uniq -u > c # c es el conjunto diferencia a - b
|
||||||
```
|
```
|
||||||
|
|
||||||
- Usa `grep . *` para examinar visualmente todo el contenido de todos los archivos de un directorio, Ej. para directorios llenos con ajustes de configuración, como `/sys`, `/proc`, `/etc`.
|
- Usa `grep . *` para rápidamente examinar el contenido de todos los archivos de un directorio (para que cada línea este emparejada con con el nombre de archivo), o `head -100 *` (para que cada archivo tenga un encabezado). Esto puede se útil para directorios llenos con ajustes de configuración como aquellos en `/sys`, `/proc`, `/etc`.
|
||||||
|
|
||||||
|
|
||||||
- Sumar todos los números en la tercera columna de un archivo de texto (esto es probablemente 3 veces más rápido y 3 veces menos código que el equivalente en Python):
|
- Sumar todos los números en la tercera columna de un archivo de texto (esto es probablemente 3 veces más rápido y 3 veces menos código que el equivalente en Python):
|
||||||
@ -295,6 +319,8 @@ Algunos ejemplos de comandos reunidos:
|
|||||||
cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn
|
cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn
|
||||||
```
|
```
|
||||||
|
|
||||||
|
- Para monitorear continuamente los cambios, usa `watch`, Ej. verificar los cambios de archivos en un directorio con `watch -d -n 2 'ls -rt1h | tail'` o para configuraciones de red mientras solucionas problemas con la configuración wifi `watch -d -n 2 ifconfig`.
|
||||||
|
|
||||||
- Ejecuta esta función para obtener un consejo aleatorio desde este documento (analiza el Markdown y extrae un elemento):
|
- Ejecuta esta función para obtener un consejo aleatorio desde este documento (analiza el Markdown y extrae un elemento):
|
||||||
```sh
|
```sh
|
||||||
function taocl() {
|
function taocl() {
|
||||||
@ -331,7 +357,7 @@ Algunos ejemplos de comandos reunidos:
|
|||||||
|
|
||||||
- `fold`: ajusta de líneas de texto
|
- `fold`: ajusta de líneas de texto
|
||||||
|
|
||||||
- `column`: formatea el texto en columnas o tablas
|
- `column`: formatea campos de texto alineados, en columnas de ancho fijo o tablas
|
||||||
|
|
||||||
- `expand` y `unexpand`: conversión entre tabuladores y espacios
|
- `expand` y `unexpand`: conversión entre tabuladores y espacios
|
||||||
|
|
||||||
@ -363,6 +389,14 @@ Algunos ejemplos de comandos reunidos:
|
|||||||
|
|
||||||
- `time`: ejecuta y calcula el tiempo de ejecución de un comando
|
- `time`: ejecuta y calcula el tiempo de ejecución de un comando
|
||||||
|
|
||||||
|
- `timeout`: ejecuta un comando especificando una cantidad de tiempo y deteniendo el proceso cuando la cantidad de tiempo especificado se completa.
|
||||||
|
|
||||||
|
- `lockfile`: crea un archivo semáforo que puedes solo ser removido con `rm -f`
|
||||||
|
|
||||||
|
- `logrotate`: rota, comprime y registra correos electrónicos.
|
||||||
|
|
||||||
|
- `watch`: ejecuta un comando repetidamente, mostrando resultados y/o resaltando cambios
|
||||||
|
|
||||||
- `tac`: imprime archivos en forma inversa
|
- `tac`: imprime archivos en forma inversa
|
||||||
|
|
||||||
- `shuf`: selección aleatoria de líneas de un archivo
|
- `shuf`: selección aleatoria de líneas de un archivo
|
||||||
@ -371,7 +405,7 @@ Algunos ejemplos de comandos reunidos:
|
|||||||
|
|
||||||
- `pv`: monitorea el progreso de datos a través de un tubo
|
- `pv`: monitorea el progreso de datos a través de un tubo
|
||||||
|
|
||||||
- `hd` y `bvi`: descarga o edita archivos binarios
|
- `hd`, `hexdump`, `xxd`, `bview` y `bvi`: descarga o edita archivos binarios
|
||||||
|
|
||||||
- `strings`: extrae texto desde archivos binarios
|
- `strings`: extrae texto desde archivos binarios
|
||||||
|
|
||||||
@ -385,6 +419,8 @@ Algunos ejemplos de comandos reunidos:
|
|||||||
|
|
||||||
- `units`: unidades de conversión y cálculos; convierte furlongs por fortnight a twips por blink (ver también `/usr/share/units/definitions.units`)
|
- `units`: unidades de conversión y cálculos; convierte furlongs por fortnight a twips por blink (ver también `/usr/share/units/definitions.units`)
|
||||||
|
|
||||||
|
- `apg`: genera contraseñas aleatorias.
|
||||||
|
|
||||||
- `7z`: compresión de archivos de alto nivel
|
- `7z`: compresión de archivos de alto nivel
|
||||||
|
|
||||||
- `ldd`: información de librería dinámica
|
- `ldd`: información de librería dinámica
|
||||||
@ -445,7 +481,7 @@ Algunos ejemplos de comandos reunidos:
|
|||||||
|
|
||||||
- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: información de hardware, incluyendo CPU, BIOS, RAID, gráficos, dispositivos, etc
|
- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: información de hardware, incluyendo CPU, BIOS, RAID, gráficos, dispositivos, etc
|
||||||
|
|
||||||
- `lsmod` y `modifno`: lista y muestra detalles de los módulos del kernel
|
- `lsmod` y `modinfo`: lista y muestra detalles de los módulos del kernel
|
||||||
|
|
||||||
- `fortune`, `ddate`, y `sl`: um, bien, depende de si considera las locomotoras de vapor y citas Zippy "útiles"
|
- `fortune`, `ddate`, y `sl`: um, bien, depende de si considera las locomotoras de vapor y citas Zippy "útiles"
|
||||||
|
|
||||||
@ -458,17 +494,23 @@ Estos son puntos relevantes *únicamente* para MacOS.
|
|||||||
|
|
||||||
- Copie la salida de cualquier comando en una aplicación de escritorio con `pbcopy` y pegue una entrada con `pbpaste`.
|
- Copie la salida de cualquier comando en una aplicación de escritorio con `pbcopy` y pegue una entrada con `pbpaste`.
|
||||||
|
|
||||||
|
- Para activar la teacla Option en un Terminal Mac OS Terminal como una tecla alt (tal como se usan en los comandos más arriba como **alt-b**, **alt-f**, etc.), abre Preferencias -> Perfiles -> Teclado y selecciona "Usa Option como tecla Meta".
|
||||||
|
|
||||||
- Para abrir un archivo con una aplicación de escritorio, use `open` o `open -a /Applications/Whatever.app`.
|
- Para abrir un archivo con una aplicación de escritorio, use `open` o `open -a /Applications/Whatever.app`.
|
||||||
|
|
||||||
- Spotlight: Busque archivos con `mdfind` y liste metadata (tal como información de foto EXIF) con `mdls`.
|
- Spotlight: Busque archivos con `mdfind` y liste metadata (tal como información de foto EXIF) con `mdls`.
|
||||||
|
|
||||||
- Ten en cuenta que MacOS está basado en BSD Unix, y muchos comandos (por ejemplo `ps`, `ls`, `tail`, `awk`, `sed`) tiene sutiles variaciones en comparación con Linux, que está en gran parte influenciado por el sistema Unix V-style y herramientas GNU. Comunmente se puede diferenciar al notar que una página man tienen el encabezado "BSD General Commands Manual." En algunos casos versiones GNU pueden ser instaladas también (tales como `gawk` y `gsed` para GNU awk y sed). Si escribe Bash scripts multiplataforma, evite tales comandos (por ejemplo, considere Python o `perl`) o prueba cuidadosamente.
|
- Ten en cuenta que MacOS está basado en BSD Unix, y muchos comandos (por ejemplo `ps`, `ls`, `tail`, `awk`, `sed`) tiene sutiles variaciones en comparación con Linux, que está en gran parte influenciado por el sistema Unix V-style y herramientas GNU. Comunmente se puede diferenciar al notar que una página man tienen el encabezado "BSD General Commands Manual." En algunos casos versiones GNU pueden ser instaladas también (tales como `gawk` y `gsed` para GNU awk y sed). Si escribe Bash scripts multiplataforma, evite tales comandos (por ejemplo, considere Python o `perl`) o prueba cuidadosamente.
|
||||||
|
|
||||||
|
- Para obtener la información de la versión del MacOS, usa `sw_vers`.
|
||||||
|
|
||||||
## Más recursos
|
## Más recursos
|
||||||
|
|
||||||
- [awesome-shell](https://github.com/alebcay/awesome-shell): Una lista curada de herramientas shell y recursos.
|
- [awesome-shell](https://github.com/alebcay/awesome-shell): Una lista curada de herramientas shell y recursos.
|
||||||
|
- [awesome-osx-command-line](https://github.com/herrbischoff/awesome-osx-command-line): Una guía más detallada para la línea de comandos del Mac OS.
|
||||||
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) para escribir mejores script shell.
|
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) para escribir mejores script shell.
|
||||||
|
- [shellcheck](https://github.com/koalaman/shellcheck): Una herramienta de análisis estadístico del script shell. Esencialmente, lint para bash/sh/zsh.
|
||||||
|
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): Las menudencias tristemente complejas sobre cómo manejar nombres de archivos correctamente en shell scripts.
|
||||||
|
|
||||||
|
|
||||||
## Advertencia
|
## Advertencia
|
||||||
|
540
README-it.md
Normal file
540
README-it.md
Normal file
@ -0,0 +1,540 @@
|
|||||||
|
[ Languages:
|
||||||
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# The Art of Command Line (Traduzione Italiana)
|
||||||
|
|
||||||
|
[](https://gitter.im/jlevy/the-art-of-command-line?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
- [Meta](#meta)
|
||||||
|
- [Le Basi](#le-basi)
|
||||||
|
- [Uso quotidiano](#uso-quotidiano)
|
||||||
|
- [Processare file e dati](#processare-file-e-dati)
|
||||||
|
- [Debug sistema](#debug-sistema)
|
||||||
|
- [One-liner](#one-liner)
|
||||||
|
- [Oscuri ma utili](#oscuri-ma-utili)
|
||||||
|
- [MacOS X](#macos-x)
|
||||||
|
- [Ulteriori risorse](#ulteriori-risorse)
|
||||||
|
- [Disclaimer](#disclaimer)
|
||||||
|
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Saper usare con una certa facilità la linea di comando è spesso visto come una sorta di "sapere arcano". Anche se può sembrare, in realtà non è decisamente così: può migliorare la tua produttività e la tua flessibilità in modi che neanche immagini. Questa che stai per leggere è una selezione di trucchi e di consigli che riguardano la linea di comando, che abbiamo trovato utili lavorando con Linux. Alcune di queste nozioni sono elementari, altre molto specifiche, se non sofisticate e, a volte, oscure.
|
||||||
|
|
||||||
|
Non c'è da preoccuparsi, comunque: la pagina che stai scorrendo non è molto lunga e non ti ruberà molto tempo. Prenderci dimestichezza, saperla usare quando necessario, te ne renderà ancora di più.
|
||||||
|
|
||||||
|
Questo lavoro è il risultato degli sforzi di [svariati autori e traduttori](AUTHORS.md).
|
||||||
|
|
||||||
|
Una buona parte di ciò che leggi è [apparsa](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands), [originariamente](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix), su [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know). Tuttavia, visto l'interesse, mi è sembrato logico usare Github per raccogliere il tutto e creare un qualcosa a cui chiunque avrebbe potuto contribuire, anche con un piccolo suggerimento. Non abbiamo la pretesa di aver creato qualcosa di perfetto: se trovi qualche errore faccelo sapere, magari aprendo una Pull Request!
|
||||||
|
|
||||||
|
|
||||||
|
## Meta
|
||||||
|
|
||||||
|
Obiettivi:
|
||||||
|
|
||||||
|
- Questa guida è adatta sia a principianti che ad utenti con più conoscenze. Ci proponiamo di seguire tre principi fondamentali: *ampiezza* (cerchiamo di includere tutto quello che serve), *specificità* (dando degli esempi concreti) e *brevità* (evitando tutto il futile e il superfluo). Ogni consiglio viene dato con l'obiettivo di salvare del tempo prezioso.
|
||||||
|
- Questa guida è stata scritta per Linux, con alcune eccezioni per che abbiamo riportato nella sezione "[MacOS X](#macos-x-only)". In ogni caso, molti dei consigli che vedrai si applicano tranquillamente ad altri sistemi operativi Unix e a MacOS.
|
||||||
|
- Il focus principale sarà su interactive Bash, nonostante non sia esclusivamente così.
|
||||||
|
- Verranno inclusi comandi "base" Unix, ma anche altri che necessiteranno di installazioni separate.
|
||||||
|
|
||||||
|
Note:
|
||||||
|
|
||||||
|
- Per tenere tutto su una sola pagina, il contenuto è stato incluso tramite reference. Crediamo che tu sia abbastanza intelligente da cercare i dettagli su qualcosa di specifico, o su un comando, usando Google. Usa `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (in base alla situazione) per installare i nuovi programmi.
|
||||||
|
- Se vuoi, usa [Explainshell](http://explainshell.com/) per avere uno spaccato più completo su cosa fanno comandi, pipe, opzioni e così via.
|
||||||
|
|
||||||
|
|
||||||
|
## Le Basi
|
||||||
|
|
||||||
|
- Impara le basi di Bash. Usa `man bash` e cerca almeno di scorrere velocemente l'intero scritto. Non è troppo lungo e neanche difficile da seguire. Altre shell possono andare bene, ma Bash è molto potente e sempre disponibile (impararne una sola tra zsh, fish e così via, per quanto ti possa tentare, ti darà problemi a lungo termine, lavorando su altre piattaforme).
|
||||||
|
|
||||||
|
- Impara ad usare bene almeno un editor di testo. Idealmente, potresti usare Vim (`vi`), con il quale non c'è praticamente competizione per questo genere di cose (si, anche se volessi usare Emacs, oppure un altro di quei grossi IDE, o magari l'ennesimo ultimo editor ultramoderno ed hipster).
|
||||||
|
|
||||||
|
- Impara a leggere la documentazione usando `man` (per i più curiosi, `man man` elenca le varie sezioni. Ad esempio, 1 indica i comandi "regolari", 5 per file/convenzioni, 8 per l'amministrazione). Trova le pagine tramite `apropos`. Ricorda inoltre che alcuni comandi non sono degli eseguibili, ma dei "builtin" di Bash. Usa `help -d` in caso di necessità.
|
||||||
|
|
||||||
|
- Impara tutto sul reindirizzamento dell'output e dell'input, usando `>`, `<` ed il pipe `|`. Impara anche che `>` sovrascrive il file output, mentre `>>` aggiunge del contenuto alla fine. Impara tutto riguardo stdout e stderr.
|
||||||
|
|
||||||
|
- Impara anche qualcosa sul file glob, l'uso di `*` (e magari anche di `?` e `[`...`]`), oltre alla differenza tra i doppi `"` e singoli `'` apici. Guarda più in giù per quanto riguarda l'espansione delle variabili.
|
||||||
|
|
||||||
|
- Acquisisci familiarità con la gestione dei job con Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, e così via.
|
||||||
|
|
||||||
|
- Impara ad usare `ssh` e le basi della passwordless authentication, tramite `ssh-agent`, `ssh-add`, e così via.
|
||||||
|
|
||||||
|
- Gestione base dei file: `ls` e `ls -l` (nello specifico, impara cosa indica ognuna delle colonne che escono fuori da `ls -l`), `less`, `head`, `tail` e `tail -f` (or even better, `less +F`), `ln` e `ln -s` (impara le differenze ed i vantaggi nell'uso di hard link o soft link), `chown`, `chmod`, `du` (per una panoramica veloce, usa: `du -hs *`). Per la gestione del filesystem, guardati `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. Impara anche cos'è un inode (`ls -i` or `df -i`).
|
||||||
|
|
||||||
|
- Gestione base delle reti: `ip` or `ifconfig`, `dig`.
|
||||||
|
|
||||||
|
- Impara ad usare per bene le espressioni regolari, e le varie flag per `grep`/`egrep`. Nello specifico, varrebbe la pena anche vedersi le opzioni `-i`, `-o`, `-v`, `-A`, `-B`, e `-C`.
|
||||||
|
|
||||||
|
- Impara ad usare `apt-get`, `yum`, `dnf` o `pacman` (in base alla distro che usi) per trovare ed installare nuovi package. E assicurati anche di aver installato `pip`, in modo tale da installare agevolmente i vari tool da linea di comando basati sul linguaggio Python. Alcuni di quelli che vedrai in seguito sono più semplici da installare se usi `pip`.
|
||||||
|
|
||||||
|
|
||||||
|
## Uso quotidiano
|
||||||
|
|
||||||
|
- In Bash, usa **Tab** per completare i vari parametri dei comandi, oppure elencarli. Usa **ctrl-r** per effettuare una ricerca nella cronologia dei comandi inseriti (premi *ctrl-r*, quindi effettua la ricerca. Per vedere più risultati premi ripetutamente *ctrl-r*). Premi quindi **Invio** per eseguire il comando trovato, oppure premi su **freccia destra** per mettere il comando sulla linea attuale, in modo tale da poterlo modificare.
|
||||||
|
|
||||||
|
- In Bash, usa **ctrl-w** per cancellare l'ultima parola, **ctrl-u** per cancellare tutto fino all'inizio della riga. Usa **alt-b** ed **alt-f** per muoverti di parola in parola. **ctrl-a** ti permette di tornare all'inizio della riga attuale senza cancellare nulla, mentre con **ctrl-e** puoi spostarti direttamente alla fine. **ctrl-k** cancella tutto quello che c'è dal punto attualmente scelto fino alla fine della riga. Inoltre, **ctrl-l** pulisce lo schermo. Per vedere una lista completa di tutte le varie scorciatoie presenti (ce ne sono molte) in bash, usa `man readline`. Ad esempio, **alt-.** serve a ciclare attraverso gli argomenti precedenti.
|
||||||
|
|
||||||
|
- In alternativa se ti piacciono le scorciatoie in stile vi, usa `set -o vi` (e `set -o emacs` per tornare indietro se dovessi cambiare idea).
|
||||||
|
|
||||||
|
- Per modificare dei comandi lunghi può essere utile impostare un editor di tua scelta (esempio: `export EDITOR=vim`). Premendo **ctrl-x** **ctrl-e** aprirai l'attuale comando in un editor multi-line per una modifica più agevole. Oppure, se stai lavorando con uno stile vi, **escape-v**.
|
||||||
|
|
||||||
|
- Per vedere i comandi più recenti, usa `history`. Ci sono anche altre abbreviazioni da usare per lo stesso scopo, come `!$` (per l'ultimo) e `!!`, nonostante questi vengano spesso rimpiazzati da **ctrl-r** e **alt-.**.
|
||||||
|
|
||||||
|
- Per tornare alla directory precedente: `cd -`
|
||||||
|
|
||||||
|
- Se stai digitando un comando, sei a metà e cambi idea, usa **alt-#** per aggiungere un `#` all'inizio della linea, rendendola di fatto un commento (oppure usa la sequenza **ctrl-a**, **#**, **invio**). Puoi quindi ritornarci dopo, tramite la cronologia.
|
||||||
|
|
||||||
|
- Usa `xargs` (o `parallel`). Si tratta di un tool molto potente, che ti permette di eseguire un certo comando tante volte quanti sono gli elementi restituiti da un altro comando. Quando non sei sicuro di quello che stai facendo, usa `xargs echo` per schiarirti le idee. Inoltre, `-I{}` è abbastanza utile. Ecco un esempio:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
find . -name '*.py' | xargs grep some_function
|
||||||
|
cat hosts | xargs -I{} ssh root@{} hostname
|
||||||
|
```
|
||||||
|
|
||||||
|
- `pstree -p` è un ottimo tool che ti mostra l'albero dei processi.
|
||||||
|
|
||||||
|
- Usa `pgrep` e `pkill` per trovare dei processi ed inviare loro un segnale specifico (`-f` è utile a riguardo).
|
||||||
|
|
||||||
|
- Impara a conoscere i vari segnali che puoi inviare ai processi. Ad esempio, per sospendere un processo puoi usare `kill -STOP [pid]`. Per una lista completa, esegui `man 7 signal`.
|
||||||
|
|
||||||
|
- Usa `nohup` o `disown` se vuoi fare in modo che un certo processo vada avanti indefinitamente.
|
||||||
|
|
||||||
|
- Controlla quali processi sono in ascolto tramite `netstat -lntp` oppure `ss -plat` (per TCP; aggiungere invece `-u` per UDP).
|
||||||
|
|
||||||
|
- Dai uno sguardo a `lsof` per un elenco di socket e file aperti.
|
||||||
|
|
||||||
|
- Usa `uptime` o `w` per sapere da quanto tempo il sistema è stato avviato.
|
||||||
|
|
||||||
|
- Usa `alias` per creare delle scorciatoie personalizzate. Ad esempio, puoi usare `alias ll='ls -latr'`, che creerà un nuovo alias `ll` per il comando `ls -latr`.
|
||||||
|
|
||||||
|
- Negli script Bash, usa `set -x` (o la variante `set -v`, che effettua un log dell'input, includendo variabili e commenti) per un migliore debug dell'output. Comunque, cerca di usare la modalità strict a meno che tu non abbia bisogno del contrario. Una buona norma suggerisce di usare lo strict mode tranne nel caso in cui tu non possa usare `set -e` per annullare un comando in caso di errore (nonzero exit code). Considera anche l'uso di `set -o pipefail`, Puoi inoltre usare `trap` su EXIT o ERR. Un'abitudine piuttosto utile è quella di iniziare uno script così, facendo in modo che annulli la propria esecuzione in caso vengano rilevati degli errori.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
set -euo pipefail
|
||||||
|
trap "echo 'error: Script failed: see failed command above'" ERR
|
||||||
|
```
|
||||||
|
|
||||||
|
- Negli script Bash, le subshell (scritte tra parentesi) sono un ottimo modo di raggruppare dei comandi. Un esempio piuttosto comune è il muoversi temporaneamente verso una directory differente, per poi tornare a lavorare in quella attuale.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# faccio qualcosa nella directory attuale
|
||||||
|
(cd /some/other/dir && other-command)
|
||||||
|
# continuo nella directory attuale
|
||||||
|
```
|
||||||
|
|
||||||
|
- In Bash esistono svariati tipi di espansione di variabile. Come controllare se una variabile esiste: `${name:?error message}`. Ad esempio, se uno script richiede un singolo parametro, scrivi `input_file=${1:?usage: $0 input_file}`. Espansione aritmetica: `i=$(( (i + 1) % 5 ))`. Sequenze: `{1..10}`. Trim di stringhe: `${var%suffix}` and `${var#prefix}`. Ad esempio, se `var=foo.pdf`, allora `echo ${var%.pdf}.txt` restituisce `foo.txt`.
|
||||||
|
|
||||||
|
- Usare la brace expansion tramite `{`...`}` può essere molto comodo in caso di necessità di automazione di alcuni task simili. Un esempio è `mv foo.{txt,pdf} some-dir` (che con un solo comando muoverà due file, il pdf ed il txt), `cp somefile{,.bak}` (che si espande a `cp somefile somefile.bak`) o `mkdir -p test-{a,b,c}/subtest-{1,2,3}` (che espande tutte le possibili combinazioni, creando un albero di directory).
|
||||||
|
|
||||||
|
- L'output di un comando può essere trattato come un file tramite `<(some command)`. Ad esempio, per comparare il file `/etc/hosts` locale con uno in remoto:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
diff /etc/hosts <(ssh somehost cat /etc/hosts)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Impara qualcosa sugli "here documents" in Bash, come `cat <<EOF ...`.
|
||||||
|
|
||||||
|
- In bash, redireziona gli errori standard (input ed output) usando: `some-command >logfile 2>&1` oppure `some-command &>logfile`. Spesso, per assicurarti che un certo comando non lasci un handle aperto "legandoti al terminale attuale" potrebbe essere una buona idea aggiungere `</dev/null`.
|
||||||
|
|
||||||
|
- Usa `man ascii` per ottenere una buona tabella ASCII, con valori decimali ed esadecimali. Per altre informazioni generali sulle codifiche, usa `man unicode`, `man utf-8`, e `man latin1`.
|
||||||
|
|
||||||
|
- Usa `screen` o [`tmux`](https://tmux.github.io/) per effettuare il multiplex della schermata, cosa particolarmente utile in caso di sessioni ssh in remoto, ad esempio. `byobu` può inoltre migliorare screen e tmux, fornendo più informazioni e una gestione semplificata. Un'altra alternativa, minimalista, per la persistenza di sessione è `dtach`.
|
||||||
|
|
||||||
|
- In ssh, sapere come effettuare il port tunneling con `-L` o `-D` (ed occasionalmente `-R`) è molto utile, ad esempio per accedere a siti web da un server remoto.
|
||||||
|
|
||||||
|
- Può essere utile effettuare alcune ottimizzazioni alla configurazione ssh; ad esempio, questo file `~/.ssh/config` contiene delle impostazioni utili ad evitare connessioni interrotte in specifiche reti ed ambienti, fa uso di compressione (utile in caso di connessioni lente), e multiplexing dei canali verso lo stesso server con un control file locale:
|
||||||
|
|
||||||
|
```
|
||||||
|
TCPKeepAlive=yes
|
||||||
|
ServerAliveInterval=15
|
||||||
|
ServerAliveCountMax=6
|
||||||
|
Compression=yes
|
||||||
|
ControlMaster auto
|
||||||
|
ControlPath /tmp/%r@%h:%p
|
||||||
|
ControlPersist yes
|
||||||
|
```
|
||||||
|
|
||||||
|
- Altre opzioni sempre interessanti riguardo ssh sono sensibili in termini di sicurezza e dovrebbero essere gestite con cura: alcuni esempi sono `StrictHostKeyChecking=no` e `ForwardAgent=yes`;
|
||||||
|
|
||||||
|
- Considera l'uso di [`mosh`](https://mosh.mit.edu/), un'alternativa ad ssh che usa UDP, in modo tale da evitare connessioni interrotte.
|
||||||
|
|
||||||
|
- Per ottenere i permessi relativi ad un certo file in forma ottale, utile alla configurazione ma non disponibile in `ls` usa qualcosa come
|
||||||
|
|
||||||
|
```sh
|
||||||
|
stat -c '%A %a %n' /etc/timezone
|
||||||
|
```
|
||||||
|
|
||||||
|
- Per una selezione interattiva di valori dall'output di un altro comando, valuta l'uso di [`percol`](https://github.com/mooz/percol) o [`fzf`](https://github.com/junegunn/fzf).
|
||||||
|
|
||||||
|
- Per interagire con dei file in base all'output di un certo comando (come `git`), usa `fpp` ([PathPicker](https://github.com/facebook/PathPicker)).
|
||||||
|
|
||||||
|
- Se vuoi creare al volo un webserver semplice, per i file nella directory attuale (sottocartelle incluse), disponibile a tutti sulla tua rete, usa:
|
||||||
|
`python -m SimpleHTTPServer 7777` (per la porta 7777 e Python 2) e `python -m http.server 7777` (per la porta 7777 e Python 3).
|
||||||
|
|
||||||
|
- Per eseguire un comando con i privilegi di un altro utente, usa `sudo` (per l'utente root) o `sudo -u` (per un altro utente). Usa `su` o `sudo bash` per eseguire la shell come tale utente. Usa `su -` per simulare un nuovo login con un altro utente.
|
||||||
|
|
||||||
|
|
||||||
|
## Processare file e dati
|
||||||
|
|
||||||
|
- Per trovare un file partendo dal suo nome nella directory attuale, usa `find . -iname '*qualcosa*'`. Per trovare un file in generale nel sistema, usa `locate qualcosa` (ma tieni a mente che `updatedb` potrebbe non ancora aver messo nell'indice i file creati da poco).
|
||||||
|
|
||||||
|
- Per una ricerca più generale, all'interno di codice sorgente o file di dati (o comunque qualcosa di più avanzato di `grep -r`), usa [`ag`](https://github.com/ggreer/the_silver_searcher).
|
||||||
|
|
||||||
|
- Per converire del codice HTML in un testo: `lynx -dump -stdin`
|
||||||
|
|
||||||
|
- Per Markdown, HTML ed ogni tipo di conversione di documenti, prova [`pandoc`](http://pandoc.org/).
|
||||||
|
|
||||||
|
- Se devi lavorare con l'XML ricorda: `xmlstarlet` è old but gold.
|
||||||
|
|
||||||
|
- Per il JSON, usa [`jq`](http://stedolan.github.io/jq/).
|
||||||
|
|
||||||
|
- Per YAML, usa [`shyaml`](https://github.com/0k/shyaml).
|
||||||
|
|
||||||
|
- Per Excel o file CSV, [csvkit](https://github.com/onyxfish/csvkit) fornisce `in2csv`, `csvcut`, `csvjoin`, `csvgrep` e così via.
|
||||||
|
|
||||||
|
- Per Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) è un ottimo tool e [`s4cmd`](https://github.com/bloomreach/s4cmd) è invece molto più veloce. Amazon [`aws`](https://github.com/aws/aws-cli) e la sua versione migliorata, [`saws`](https://github.com/donnemartin/saws) sono qualcosa di fondamentale per ogni tipo di task legato ad AWS.
|
||||||
|
|
||||||
|
- Impara di più riguardo `sort` ed `uniq`, incluso `-u` e `-d` di `uniq`. Guardati anche `comm`.
|
||||||
|
|
||||||
|
- Impara a conoscere meglio anche `cut`, `paste` e `join` per manipolare file di testo. Molte persone spesso usano `cut` ma si scordano dell'esistenza di `join`.
|
||||||
|
|
||||||
|
- Impara ad usare `wc` per contare i ritorni a capo (`-l`), caratteri (`-m`), parole (`-w`) e byte (`-c`).
|
||||||
|
|
||||||
|
- Impara qualcosa di più riguardo `tee` per copiare da stdin ad un file ed anche verso stdout. Esempio: `ls -al | tee file.txt`.
|
||||||
|
|
||||||
|
- Ricorda che le impostazioni riguardo la localizzazione influiscono un sacco su alcuni tool da linea di comando, in molti modi. Ad esempio sugli ordinamenti (collation) e performance. Molte installazioni Linux impostano `LANG` ed altre variabili correlate automaticamente su US English (inglese americano). Se decidi di cambiare lingua, non è detto quindi che le cose rimangano così come sono. Alcuni comandi, addirittura, potrebbero diventare immediatamente molto più lenti.
|
||||||
|
|
||||||
|
- Impara le basi di `awk` e `sed` per manipolare dati. Ad esempio, per sommare tutti i numeri nella terza colonna di un file di testo, usa `awk '{ x += $3 } END { print x }'`. Probabilmente tre volte più veloce e tre volt epiù corto del suo equivalente in Python.
|
||||||
|
|
||||||
|
- Per rimpiazzare tutte le occorrenze di una stringa, in uno o più file:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
- Per rinominare dei file in massa e per effettuare cerca/sostituisci al loro interno, prova anche [`repren`](https://github.com/jlevy/repren). (In alcuni casi il comando `rename` permette operazioni multiple, ma fai attenzione al risultato visto che la funzionalità non è sempre identica sulle varie distro;
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Full rename of filenames, directories, and contents foo -> bar:
|
||||||
|
repren --full --preserve-case --from foo --to bar .
|
||||||
|
# Recover backup files whatever.bak -> whatever:
|
||||||
|
repren --renames --from '(.*)\.bak' --to '\1' *.bak
|
||||||
|
# Same as above, using rename, if available:
|
||||||
|
rename 's/\.bak$//' *.bak
|
||||||
|
```
|
||||||
|
|
||||||
|
- Come la pagina del manuale spiega, `rsync` è un ottimo tool per copiare file, versatile e velocissimo. Si, è conosciuto per sincronizzare file da una macchina all'altra, ma è ugualmente utile se viene usato localmente. Viene anche riconosciuto come [uno dei modi più veloci](https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html) di cancellare un grande numero di file tutti insieme:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
|
||||||
|
```
|
||||||
|
|
||||||
|
- Usa `shuf` per selezionare una serie di linee da un file, in ordine casuale.
|
||||||
|
|
||||||
|
- Impara a conoscere le opzioni di `sort`. Per i numeri, usa `-n`, oppure `-h` per gestire numeri leggibili dal'uomo (`du -h`). Impara a capire come funzionano le varie chiavi (`-t` e `-k`). In particolare, fai attenzione a quando scrivi `-k1,1` per ordinare solo per il valore del primo campo, visto che `-k1` significa ordinare secondo l'intera riga. Lo stable sort (`sort -s`) può esserti utile. Immagina ad esempio di voler ordinare secondo il valore del secondo campo, e secondariamente del primo. Userai `sort -k1,1 | sort -s -k2,2`.
|
||||||
|
|
||||||
|
- Se dovessi aver bisogno di scrivere, letteralmente, un tab in Bash, premi **ctrl-v** **[Tab]** o scrivi `$'\t'`.
|
||||||
|
|
||||||
|
- I tool standard per il patching del codice sono `diff` e `patch`. Guarda anche Guarda anche `diffstat` per saperne di più su una diff e `sdiff` per una side-by-side diff. Nota bene che `diff -r` lavora con intere directory. Usa `diff -r tree1 tree2 | diffstat` per una panoramica dei cambiamenti. Usa `vimdiff` per comparare e modificare file.
|
||||||
|
|
||||||
|
- Per file binari, usa `hd`, `hexdump` o `xxd` per semplici hex dump, e `bvi` o `biew` per editing binario.
|
||||||
|
|
||||||
|
- Inoltre, sempre per file binari, usa `strings` (insieme `grep`, e così via) per trovare sezioni di testo al loro interno;
|
||||||
|
|
||||||
|
- Per diff binarie (delta compression), usa `xdelta3`.
|
||||||
|
|
||||||
|
- Per convertire un testo da una codifica ad un'altra, prova `iconv`. Oppure `uconv` in caso di necessità più avanzate; supporta svariate opzioni avanzate inerenti Unicode. Ad esempio, questo comando rimuove tutti gli accenti e trasforma le stringhe in lettere tutte minuscole:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC; ' < input.txt > output.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
- Per dividere un file in altri file più piccoli, guarda `split` (per dividere in base alla dimensione) e `csplit` (per dividere in base ad un pattern).
|
||||||
|
|
||||||
|
- Se devi manipolare date ed orari, usa `dateadd`, `datediff`, `strptime` e così via, di [`dateutils`](http://www.fresse.org/dateutils/).
|
||||||
|
|
||||||
|
- Usa `zless`, `zmore`, `zcat` e `zgrep` per lavorare su file compressi.
|
||||||
|
|
||||||
|
|
||||||
|
## Debug sistema
|
||||||
|
|
||||||
|
- Per il web debugging, `curl` e `curl -I` sono decisamente utili. La stessa cosa vale anche per l'equivalente `wget`, o ancora per il più recente [`httpie`](https://github.com/jkbrzt/httpie).
|
||||||
|
|
||||||
|
- Per avere più informazioni sullo stato attuale del sistema, dalla cpu ai dischi, il tool classico più usato è `top` (o la sua versione migliorata `htop`), `iostat` e `iotop`. Usa `iostat -mxz 15` per avere informazioni base sulla CPU ed informazioni dettagliate, per partizione, sui dischi e sulle loro performance.
|
||||||
|
|
||||||
|
- Per avere più dettagli sulle connessioni di rete, usa `netstat` e `ss`.
|
||||||
|
|
||||||
|
- Per una panoramica veloce di cosa sta succedendo nel sistema, `dstat` è ottimo. Per avere invece molte più informazioni e scendere nel dettaglio, usa [`glances`](https://github.com/nicolargo/glances).
|
||||||
|
|
||||||
|
- Per saperne di più sullo stato della memoria, esegui ed impara a capire il significato dei comandi `free` e `vmstat`. In particolare, sii consapevole del fatto che la memoria "cached" è quella mantenuta dal kernel Linux come file cache, che a tutti gli effetti poi conta come memoria libera.
|
||||||
|
|
||||||
|
- Il system debugging con Java è tutta un'altra cosa. Uno dei trucchi più semplici sulla JVM Oracle (ed anche altre) è che all'esecuzione di `kill -3 <pid>` verrà messo in log un trace full stack (inclusi molti dettagli sulla garbage collection). Anche `jps`, `jstat`, `jstack` e `jmap` del JDK sono molto utili. Ci sono poi i vari [SJK tools](https://github.com/aragozin/jvm-tools), più avanzati.
|
||||||
|
|
||||||
|
- Usa `mtr` per rilevare problemi di rete. Molto meglio di traceroute.
|
||||||
|
|
||||||
|
- Per capire perché un disco viene visto pieno, `ncdu` ti evita perdite di tempo rispetto al più comune `du -sh *`.
|
||||||
|
|
||||||
|
- Per capire quale socket o processo sta usando troppa banda prova `iftop` o `nethogs`.
|
||||||
|
|
||||||
|
- `ab` (incluso in Apache) è ottimo per un test di carico veloce di un webserver. Per test di carico più avanzati, prova anche `siege`.
|
||||||
|
|
||||||
|
- Per un debug di rete più avanzato, dai uno sguardo a `wireshark`, `tshark` o `ngrep`.
|
||||||
|
|
||||||
|
- Impara qualcosa di più su `strace` e `ltrace`. Possono essere molto utili quando un programma crasha, o magari rimane in blocco e tu non capisci perché. Degne di nota le opzioni di profiling (`-c`), e la possibilità di agganciare un processo in esecuzione (`-p`).
|
||||||
|
|
||||||
|
- Impara qualcosa di più riguardo `ldd` per controllare le librerie condivise.
|
||||||
|
|
||||||
|
- Impara a connetterti ad un processo in esecuzione con `gdb` e recuperare il suo stack trace.
|
||||||
|
|
||||||
|
- Usa `/proc`. Fantastico quando devi fare un live debug in caso di problemi. Esempi: `/proc/cpuinfo`, `/proc/meminfo`, `/proc/cmdline`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps` (dove `xxx` è il nome del processo o il suo pid).
|
||||||
|
|
||||||
|
- Quando vuoi debuggare qualcosa che è andato storto in passato, `sar` può essere molto utile. Permette di controllare uno storico delle statistiche di CPU, memoria, rete e così via.
|
||||||
|
|
||||||
|
- Usa `stap` per un'analisi più approfondita del sistema in termini di performance ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](https://en.wikipedia.org/wiki/Perf_(Linux)), e [`sysdig`](https://github.com/draios/sysdig).
|
||||||
|
|
||||||
|
- Controlla quale OS stai usando con `uname` oppure `uname -a` (informazioni generali sul kernel) o `lsb_release -a` (informazioni sulla distro Linux).
|
||||||
|
|
||||||
|
- Usa `dmesg` quando il sistema si comporta in modo davvero strano (problemi hardware o legati ai driver, insomma).
|
||||||
|
|
||||||
|
|
||||||
|
## One-liner
|
||||||
|
|
||||||
|
Qualche esempio di combinazione di più comandi comandi:
|
||||||
|
|
||||||
|
- Decisamente è utile è sapere che puoi effettuare intersesione, unione e differenza di file di testo tramite `sort`/`uniq`. Immagina di avere `a` e `b`, due file di testo. Il metodo in questione è veloce e tra l'altro supporta anche file di svariati gigabyte. Guarda anche la nota riguardo `LC_ALL` e l'opzione `-u` di `sort`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cat a b | sort | uniq > c # c is a union b
|
||||||
|
cat a b | sort | uniq -d > c # c is a intersect b
|
||||||
|
cat a b b | sort | uniq -u > c # c is set difference a - b
|
||||||
|
```
|
||||||
|
|
||||||
|
- Usa `grep . *` per esaminare velocemente i contenuti di tutti i file in una certa directory (in modo che ogni linea venga abbinata al nome del file), oppure `head -100 *`. Può essere molto utile per quelle directory piene file di configurazione, come `/sys`, `/proc`, `/etc`.
|
||||||
|
|
||||||
|
|
||||||
|
- Sommare tutti i numeri sulla terza colonna di un file di testo (probabilmente 3 volte più veloce e corto della controparte in Python):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
awk '{ x += $3 } END { print x }' myfile
|
||||||
|
```
|
||||||
|
|
||||||
|
- Nel caso in cui tu voglia vedere dimensioni e date per un certo "albero" di file (un po' come `ls -l`, ma ricorsivo):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
find . -type f -ls
|
||||||
|
```
|
||||||
|
|
||||||
|
- Immagina di avere un file di testo, come un log di un server, like a web server log, ed un certo valore appare di tanto in tanto tra le righe, come ad esempio un parametro `acct_id` in un URL.. Ecco come contare le richieste effettuate che contengono tale parametro `acct_id`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn
|
||||||
|
```
|
||||||
|
|
||||||
|
- Per monitorare costantemente i cambiamenti ai file, usa `watch`. Ad esempio, per controllare i cambiamneti in una certa directory usa `watch -d -n 2 'ls -rtlh | tail'` oppure, se stai monitorando un file di configurazione inerente il WiFi, `watch -d -n 2 ifconfig`.
|
||||||
|
|
||||||
|
- Esegui questa funzione per ottenere un consiglio a caso da questo documento:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
function taocl() {
|
||||||
|
curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md |
|
||||||
|
pandoc -f markdown -t html |
|
||||||
|
xmlstarlet fo --html --dropdtd |
|
||||||
|
xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" |
|
||||||
|
xmlstarlet unesc | fmt -80
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Oscuri ma utili
|
||||||
|
|
||||||
|
- `expr`: esegue operazioni aritmetiche o booleane, oltre a valutare espressioni regolari.
|
||||||
|
|
||||||
|
- `m4`: un semplice macro processor.
|
||||||
|
|
||||||
|
- `yes`: stampa una stringa per un numero indefinito di volte.
|
||||||
|
|
||||||
|
- `cal`: un calendario.
|
||||||
|
|
||||||
|
- `env`: esegue un comando (utile negli script).
|
||||||
|
|
||||||
|
- `printenv`: stampa le variabili di ambiente (utile per il debug e negli script).
|
||||||
|
|
||||||
|
- `look`: trova parole inglesi (o linee in un file) partendo da una stringa.
|
||||||
|
|
||||||
|
- `cut`, `paste` e `join`: manipolazione di dati.
|
||||||
|
|
||||||
|
- `fmt`: formatta paragrafi di testo.
|
||||||
|
|
||||||
|
- `pr`: formatta del testo in pagine/colonne.
|
||||||
|
|
||||||
|
- `fold`: sistema delle linee di testo.
|
||||||
|
|
||||||
|
- `column`: formatta del testo in colonne o tabelle dalla larghezza fissa.
|
||||||
|
|
||||||
|
- `expand` ed `unexpand`: converte spazi in tab, e viceversa.
|
||||||
|
|
||||||
|
- `nl`: aggiunge il conteggio delle righe.
|
||||||
|
|
||||||
|
- `seq`: stampa dei numeri.
|
||||||
|
|
||||||
|
- `bc`: calcolatrice.
|
||||||
|
|
||||||
|
- `factor`: scompone un numero in fattori.
|
||||||
|
|
||||||
|
- [`gpg`](https://gnupg.org/): cripta e firma i file.
|
||||||
|
|
||||||
|
- `toe`: tabella di tutti i terminali disponbili.
|
||||||
|
|
||||||
|
- `nc`: per il network debugging e trasferimento dati.
|
||||||
|
|
||||||
|
- `socat`: socket relay e tcp port forwarder (simile a `netcat`).
|
||||||
|
|
||||||
|
- [`slurm`](https://github.com/mattthias/slurm): visualizzazione del traffico di rete.
|
||||||
|
|
||||||
|
- `dd`: spostamento dati tra file e dispositivi.
|
||||||
|
|
||||||
|
- `file`: identifica il tipo di un certo file.
|
||||||
|
|
||||||
|
- `tree`: mostra le sottodirectory con una struttura ad albero. A differenza di `ls`, è ricorsivo.
|
||||||
|
|
||||||
|
- `stat`: informazioni su un file.
|
||||||
|
|
||||||
|
- `time`: esegue un comando e tiene traccia del tempo di esecuzione.
|
||||||
|
|
||||||
|
- `timeout`: avvia un comando definendo anche un certo ammontare di tempo oltre il quale non si può andare. Se tale ammontare di tempo viene raggiunto, il comando viene annullato.
|
||||||
|
|
||||||
|
- `lockfile`: crea un file che può essere rimosso solo tramite `rm -f`.
|
||||||
|
|
||||||
|
- `logrotate`: gestie i log, la loro rotazione, compressione ed invio via mail.
|
||||||
|
|
||||||
|
- `watch`: esegue un comando più volte, mostrando i risultati ed evidenziando le differenze tra tali risultati.
|
||||||
|
|
||||||
|
- `tac`: stampa un file al contrario.
|
||||||
|
|
||||||
|
- `shuf`: sceglie casualmente delle righe da un file.
|
||||||
|
|
||||||
|
- `comm`: compara dei file ordinati riga per riga.
|
||||||
|
|
||||||
|
- `pv`: monitora i progressi dei dati attraverso un pipe.
|
||||||
|
|
||||||
|
- `hd`, `hexdump`, `xxd`, `biew` e `bvi`: dump o modifica di file binari.
|
||||||
|
|
||||||
|
- `strings`: estrae del testo da file binari.
|
||||||
|
|
||||||
|
- `tr`: manipolazione e trasformazione dei caratteri.
|
||||||
|
|
||||||
|
- `iconv` o `uconv`: conversione di testi in altre codifiche.
|
||||||
|
|
||||||
|
- `split` e `csplit`: divisione di un file in altri file più piccoli.
|
||||||
|
|
||||||
|
- `sponge`: legge tutto l'input prima di riscriverlo, utile in caso di lettura e scrittura sullo stesso file. Ad esempio: `grep -v something some-file | sponge some-file`.
|
||||||
|
|
||||||
|
- `units`: conversione da e verso altre unità di misura (guarda anche `/usr/share/units/definitions.units`).
|
||||||
|
|
||||||
|
- `apg`: genera password casuali.
|
||||||
|
|
||||||
|
- `7z`: compressione di file ad alta ratio.
|
||||||
|
|
||||||
|
- `ldd`: informazioni su una libreria dinamica.
|
||||||
|
|
||||||
|
- `nm`: elenca i vari simboli presenti un object file.
|
||||||
|
|
||||||
|
- `ab`: benchmark di webserver.
|
||||||
|
|
||||||
|
- `strace`: debug delle chiamate di sistema.
|
||||||
|
|
||||||
|
- `mtr`: un traceroute migliore per il debug di rete.
|
||||||
|
|
||||||
|
- `cssh`: shell visuale concorrente.
|
||||||
|
|
||||||
|
- `rsync`: sincronizza file e cartelle tramite SSH oppure in locale.
|
||||||
|
|
||||||
|
- `wireshark` e `tshark`: packet capturing e debug di rete.
|
||||||
|
|
||||||
|
- `ngrep`: come grep... ma per il traffico di rete.
|
||||||
|
|
||||||
|
- `host` e `dig`: DNS lookup.
|
||||||
|
|
||||||
|
- `lsof`: descrittore dei processi ed informazioni su socket.
|
||||||
|
|
||||||
|
- `dstat`: statistiche di sistema.
|
||||||
|
|
||||||
|
- [`glances`](https://github.com/nicolargo/glances): overview di sistemi multipli ad alto livello.
|
||||||
|
|
||||||
|
- `iostat`: statistiche sull'uso dei dischi.
|
||||||
|
|
||||||
|
- `mpstat`: statistiche sull'uso della CPU.
|
||||||
|
|
||||||
|
- `vmstat`: statistiche sull'uso della memoria.
|
||||||
|
|
||||||
|
- `htop`: versione migliorata di top.
|
||||||
|
|
||||||
|
- `last`: cronologia dei login.
|
||||||
|
|
||||||
|
- `w`: mostra chi è autenticato.
|
||||||
|
|
||||||
|
- `id`: user/group identity info.
|
||||||
|
|
||||||
|
- `sar`: cronologia di alcune statistiche del sistema.
|
||||||
|
|
||||||
|
- `iftop` o `nethogs`: uso della rete da parte di socket e processi.
|
||||||
|
|
||||||
|
- `ss`: statistiche sui socket.
|
||||||
|
|
||||||
|
- `dmesg`: messaggi di errore di avvio e di sistema in generale.
|
||||||
|
|
||||||
|
- `sysctl`: visualizza e configura i parametri del kernel a run time.
|
||||||
|
|
||||||
|
- `hdparm`: tool di gestione dischi SATA/ATA.
|
||||||
|
|
||||||
|
- `lsb_release`: informazioni sulla distribuzione Linux.
|
||||||
|
|
||||||
|
- `lsblk`: visualizzazione ad albero dei dischi e relative partizioni.
|
||||||
|
|
||||||
|
- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: informazioni sull'hardware, tra cui CPU, BIOS, RAID, scheda grafica e dispositivi di ogni tipo.
|
||||||
|
|
||||||
|
- `lsmod` e `modinfo`: elenco e dettaglio dei vari moduli del kernel.
|
||||||
|
|
||||||
|
- `fortune`, `ddate`, e `sl`: mmmh, beh, dipende molto da quanto consideri le locomotive a vapore e le citazioni di Zippy "utili".
|
||||||
|
|
||||||
|
|
||||||
|
## MacOS X
|
||||||
|
|
||||||
|
Consiera questa sezione come un'esclusiva MacOS.
|
||||||
|
|
||||||
|
- I package vengono gestiti con `brew` (Homebrew) e/o `port` (MacPorts). Possono essere usati su MacOS per installare molti dei comandi visti in questo articolo.
|
||||||
|
|
||||||
|
- Copia l'output di un qualsiasi comando tramite `pbcopy` ed incollalo, invece, con `pbpaste`.
|
||||||
|
|
||||||
|
- Per abilitare l'Option key sul terminale Mac OS come un'alt key (per riprodurre comandi quali **alt-b**, **alt-f**, e così via), apri Preferenze -> Profili -> Tastiera e scegli "Usa Option come meta key".
|
||||||
|
|
||||||
|
- Per aprire un file con un'applicazione desktop, usa `open` oppure `open -a /Applications/LaTuaApplicazione.app`.
|
||||||
|
|
||||||
|
- Cerca i file con `mdfind` ed elenca i vari metadati (come gli EXIF per le foto) con `mdls`.
|
||||||
|
|
||||||
|
- Sii consapevole del fatto che MacOS è basato su BSD Unix, e molti dei suoi comandi (ad esempio `ps`, `ls`, `tail`, `awk`, `sed`) presentano alcune variazioni rispetto alla loro controparte Linux. Per controllare tali differenze devi vedere se la pagina del manuale ha come titolo "BSD General Commands Manual". Come logica conseguenza, quindi, ricorda di non usare tali comandi se hai intenzione di scrivere degli script cross-platform.
|
||||||
|
|
||||||
|
- Per avere più informazioni sulla tua release di MacOS, usa `sw_vers`.
|
||||||
|
|
||||||
|
|
||||||
|
## Ulteriori risorse
|
||||||
|
|
||||||
|
- [awesome-shell](https://github.com/alebcay/awesome-shell): Una curatissima lista di tool e risorse
|
||||||
|
- [awesome-osx-command-line](https://github.com/herrbischoff/awesome-osx-command-line): Una guida approfondita sulla linea di comando in Mac OSX
|
||||||
|
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) per scrivere script migliori
|
||||||
|
- [shellcheck](https://github.com/koalaman/shellcheck): Un tool di analisi per script shell. Praticamente lint per bash/sh/zsh.
|
||||||
|
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): Un compendio sul come gestire nomi dei file e path nella shell
|
||||||
|
|
||||||
|
|
||||||
|
## Disclaimer
|
||||||
|
|
||||||
|
Con l'eccezione di pochi piccoli task, il codice è stato scritto per permettere agli altri di leggerlo agevolmente. Da grandi poteri derivano grandi responsabilità. Ricorda: il fatto che tu possa *fare* qualcosa in Bash non implica comunque che tu debba per forza! ;)
|
||||||
|
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
[](http://creativecommons.org/licenses/by-sa/4.0/)
|
||||||
|
|
||||||
|
A questo lavoro è attribuita la [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/).
|
18
README-ja.md
18
README-ja.md
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
原文のコミット [bb0c38c0899339e836c37eead4a9534b06c56662](https://github.com/jlevy/the-art-of-command-line/blob/bb0c38c0899339e836c37eead4a9534b06c56662/README.md)
|
原文のコミット [bb0c38c0899339e836c37eead4a9534b06c56662](https://github.com/jlevy/the-art-of-command-line/blob/bb0c38c0899339e836c37eead4a9534b06c56662/README.md)
|
||||||
@ -20,21 +20,21 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
コマンドラインで流れるように操作ができるということは、軽く見られたり他人から理解されないスキルだとみなされることもあるでしょう。しかしそのスキルは、明らかにかすぐ分かるようかは問わず、エンジニアとしてのあなたの柔軟性や生産性を改善してくれるものです。ここでは、Linuxでコマンドラインを使う上で便利だと思ったメモやTipsの数々を挙げてみます。あるものは基礎的ですが、非常に詳しいもの、洗練されたもの、曖昧なものもあります。このページはそんなに長いものではないですが、ここに書いてあることの全てを使ったり思い出すことができれば、かなり詳しくなれるでしょう。
|
コマンドラインで流れるように操作ができるということは、軽く見られたり他人から理解されないスキルだとみなされることもあるだろう。しかしそのスキルは、明らかにかすぐ分かるようかは問わず、エンジニアとしてのあなたの柔軟性や生産性を改善してくれるものだ。ここでは、Linuxでコマンドラインを使う上で便利だと思ったメモやTipsの数々を挙げてみる。あるものは基礎的だが、非常に詳しいもの、洗練されたもの、曖昧なものもある。このページはそんなに長いものではないが、ここに書いてあることの全てを使ったり思い出すことができれば、かなり詳しくなれるだろう。
|
||||||
|
|
||||||
ここに書いてあることの多くは、[元々](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands)[Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know)に[書かれて](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix)いたものが多いですが、私よりももっと優れた人たちがすぐに改善案を出すことができるGithubに置くのがよいのではと思ったのです(訳注 : 原文はGithub上にあります)。間違いやもっとこうした方がよいという点があれば、イシューを登録するかプルリクエストをください!(もちろん、メタ情報の項や既存のプルリクエスト、イシューをまず確認してください)
|
ここに書いてあることの多くは、[元々](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands)[Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know)に[書かれて](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix)いたものが多いが、私よりももっと優れた人たちがすぐに改善案を出すことができるGithubに置くのがよいのではと思った(訳注 : 原文はGithub上にある)。間違いやもっとこうした方がよいという点があれば、イシューを登録するかプルリクエストを送ってほしい!(もちろん、メタ情報の項や既存のプルリクエスト、イシューをまず確認しよう)
|
||||||
|
|
||||||
## メタ情報
|
## メタ情報
|
||||||
|
|
||||||
対象 :
|
対象 :
|
||||||
|
|
||||||
- このガイドは、初心者向けでも経験者向きでもあります。幅広く(書いてあることは全て重要)、かつ明確で(多くのケースに対して具体的な例を付ける)、そして簡潔(他の場所で見つけられるような重要でないことや脱線したことは省く)であることをゴールにしています。各項目は、多くの場面において必須であるか、他の方法に比べて劇的に時間を節約してくれるでしょう。
|
- このガイドは、初心者向けでも経験者向きでもある。幅広く(書いてあることは全て重要)、かつ明確で(多くのケースに対して具体的な例を付ける)、そして簡潔(他の場所で見つけられるような重要でないことや脱線したことは省く)であることをゴールにしている。各項目は、多くの場面において必須であるか、他の方法に比べて劇的に時間を節約してくれるだろう。
|
||||||
- Linux向けに書いています。多くはMacOS(あるいはCygwin)でも使えますが、全部ではありません。
|
- Linux向けに書いている。多くはMacOS(あるいはCygwin)でも使えるが、全部ではない。
|
||||||
- インタラクティブなBashを使うことを想定していますが、多くの項目は他のシェルやBashのスクリプトでも使えるでしょう。
|
- インタラクティブなBashを使うことを想定しているが、多くの項目は他のシェルやBashのスクリプトでも使えるだろう。
|
||||||
|
|
||||||
注意 :
|
注意 :
|
||||||
|
|
||||||
- 1ページ内に収めるために、内容には暗黙的に書かれていることがあります。ここで取りかかりを知ったりコマンドが分かれば、詳細をどこかで調べたりするくらいはできるでしょう。新しいプログラムをインストールするには、`apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew`(どれか適したもの)を使いましょう。
|
- 1ページ内に収めるために、内容には暗黙的に書かれていることがある。ここで取りかかりを知ったりコマンドが分かれば、詳細をどこかで調べたりするくらいはできるだろう。新しいプログラムをインストールするには、`apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew`(どれか適したもの)を使おう。
|
||||||
- コマンドやオプション、パイプを分解して理解する手助けに、[Explainshell](http://explainshell.com/)を使おう。
|
- コマンドやオプション、パイプを分解して理解する手助けに、[Explainshell](http://explainshell.com/)を使おう。
|
||||||
|
|
||||||
## 基本
|
## 基本
|
||||||
@ -447,10 +447,10 @@
|
|||||||
|
|
||||||
## 免責事項
|
## 免責事項
|
||||||
|
|
||||||
ごく一部の例外はありますが、コードは誰でも読めるように書かれています。力には責任が伴います。Bashで*できる*からといって、そうすべき必要があるという意味ではありません! ;)
|
ごく一部の例外はありますが、コードは誰でも読めるように書かれている。力には責任が伴う。Bashで*できる*からといって、そうすべき必要があるという意味ではない! ;)
|
||||||
|
|
||||||
## ライセンス
|
## ライセンス
|
||||||
|
|
||||||
[](http://creativecommons.org/licenses/by-sa/4.0/)
|
[](http://creativecommons.org/licenses/by-sa/4.0/)
|
||||||
|
|
||||||
このドキュメントは[Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/)でライセンスされます。
|
このドキュメントは[Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/)でライセンスされる。
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
37
README-sl.md
37
README-sl.md
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -21,13 +21,14 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
Jedrnatost v ukazni vrstici je znanje, ki je pogostokrat zanemarjeno ali smatrano za zastarelo, vendar izboljša vašo fleksibilnost in produktivnost kot inženir na očitne in neočitne načine. To so izbrani zapiski in nasveti glede uporabe ukazne vrstice, ki sem jo našel uporabno pri delu z Linux-om. Nekateri nasveti so elementarni in nekateri so precej določeni, sofisticirani ali nepregledni. Ta stran ni dolga, vendar če lahko uporabite in se spomnite vseh elementov tu, boste vedeli veliko.
|
Jedrnatost v ukazni vrstici je znanje, ki je pogostokrat zanemarjeno ali smatrano za zastarelo, vendar izboljša vašo fleksibilnost in produktivnost kot inženir na očitne in neočitne načine. To so izbrani zapiski in nasveti glede uporabe ukazne vrstice, ki smo jo našli uporabno pri delu z Linux-om. Nekateri nasveti so elementarni in nekateri so precej določeni, sofisticirani ali nepregledni. Ta stran ni dolga, vendar če lahko uporabite in se spomnite vseh elementov tu, boste vedeli veliko.
|
||||||
|
|
||||||
|
To delo je rezultat [mnogih avtorjev in prevajalcev](AUTHORS.md).
|
||||||
Veliko tega
|
Veliko tega
|
||||||
se [prvotno](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands)
|
se [prvotno](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands)
|
||||||
[pojavi](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix)
|
[pojavi](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix)
|
||||||
na [Quori](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),
|
na [Quori](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),
|
||||||
vendar glede na dani interes tu, izgleda vredno uporabe GitHub-a, kjer ljudje bolj talentirani kot jaz lahko bralno predlagajo izboljšave. Če opazite napako ali nekaj, kar je lahko bolje, prosim, pošljite težavo ali zahtevek potega (PR)! (Seveda, prosim preglejte meta sekcijo in obstoječe težave/zahtevke potega najprej.)
|
vendar glede na dani interes tu, izgleda vredno uporabe GitHub-a, kjer lahko ljudje bolj talentirani od prvotnega avtorja takoj predlagajo izboljšave. Če opazite napako ali nekaj, kar je lahko bolje, prosim, pošljite težavo ali zahtevek potega (PR)! (Seveda, prosim preglejte meta sekcijo in obstoječe težave/zahtevke potega najprej.)
|
||||||
|
|
||||||
|
|
||||||
## Meta
|
## Meta
|
||||||
@ -208,12 +209,19 @@ Opombe:
|
|||||||
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
- Da preimenujete mnoge datoteke naenkrat glede na vzorec, uporabite `rename`. Za kompleksna preimenovanja lahko pomaga [`repren`](https://github.com/jlevy/repren).
|
- Da preimenujete več datotek in/ali poiščete in poiščete in zamenjate znotraj datotek, poskusite [`repren`](https://github.com/jlevy/repren). (V nekaterih primerih ukaz `rename` tudi omogoča preimenovanje, vendar bodite pozorni, saj funkcionalnost ni enaka na vseh distribucijah Linux).
|
||||||
```sh
|
```sh
|
||||||
# Recover backup files foo.bak -> foo:
|
|
||||||
rename 's/\.bak$//' *.bak
|
|
||||||
# Full rename of filenames, directories, and contents foo -> bar:
|
# Full rename of filenames, directories, and contents foo -> bar:
|
||||||
repren --full --preserve-case --from foo --to bar .
|
repren --full --preserve-case --from foo --to bar .
|
||||||
|
# Recover backup files whatever.bak -> whatever:
|
||||||
|
repren --renames --from '(.*)\.bak' --to '\1' *.bak
|
||||||
|
# Same as above, using rename, if available:
|
||||||
|
rename 's/\.bak$//' *.bak
|
||||||
|
```
|
||||||
|
|
||||||
|
- Kot pravi stran vodiča, je `rsync` resnično hiter in izredno vsestransko orodje kopiranja datotek. Znano je po sinhronizaciji med napravami vendar je enakovredno uporaben tudi lokalno. Je tudi eden izmed [najhitrejših načinov](https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html) za izbris velikega števila datotek:
|
||||||
|
```sh
|
||||||
|
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
|
||||||
```
|
```
|
||||||
|
|
||||||
- Uporabite `shuf` za naključno mešanje ali izbiro naključnih vrstic iz datoteke.
|
- Uporabite `shuf` za naključno mešanje ali izbiro naključnih vrstic iz datoteke.
|
||||||
@ -224,7 +232,7 @@ Opombe:
|
|||||||
|
|
||||||
- Standardna orodja za popravljanje izvorne kode so `diff` in `patch`. Glejte tudi `diffstat` za povzetek statistike diff-a in `sdiff` za diff drug ob drugem. Bodite pozorni, saj `diff -r` deluje za celotne direktorije. Uporabite `diff -r tree1 tree2 | diffstat` za povzetek sprememb. Uporabite `vimdiff` za primerjanje in urejanje datotek.
|
- Standardna orodja za popravljanje izvorne kode so `diff` in `patch`. Glejte tudi `diffstat` za povzetek statistike diff-a in `sdiff` za diff drug ob drugem. Bodite pozorni, saj `diff -r` deluje za celotne direktorije. Uporabite `diff -r tree1 tree2 | diffstat` za povzetek sprememb. Uporabite `vimdiff` za primerjanje in urejanje datotek.
|
||||||
|
|
||||||
- Pri binarnih datotekah uporabite `hd` za enostavne heksadecimalne izpise in `bvi` za binarno urejanje.
|
- Pri binarnih datotekah uporabite `hd`, `hexdump` ali `xxd` za enostavne heksadecimalne izpise in `bvi` ali `biew` za binarno urejanje.
|
||||||
|
|
||||||
- `strings` (plus `grep` itd.) vam omogoča najti bite v tekstu tudi za binarne datoteke.
|
- `strings` (plus `grep` itd.) vam omogoča najti bite v tekstu tudi za binarne datoteke.
|
||||||
|
|
||||||
@ -237,14 +245,14 @@ Opombe:
|
|||||||
|
|
||||||
- Da razcepite datoteke na dele, glejte `split` (da razcepite po velikosti) in `csplit` (da razcepite po vzorcu).
|
- Da razcepite datoteke na dele, glejte `split` (da razcepite po velikosti) in `csplit` (da razcepite po vzorcu).
|
||||||
|
|
||||||
- Za manipuliranje izrazov datuma in časa, uporabite `dateadd`, `datediff`, `strptime` itd. iz [`dateutils`](http://www.fresse.org/dateutils).
|
- Za manipuliranje izrazov datuma in časa, uporabite `dateadd`, `datediff`, `strptime` itd. iz [`dateutils`](http://www.fresse.org/dateutils/).
|
||||||
|
|
||||||
- Uporabite `zless`, `zmore`, `zcat` in `zgrep` za operiranje na kompresiranih datotekah.
|
- Uporabite `zless`, `zmore`, `zcat` in `zgrep` za operiranje na kompresiranih datotekah.
|
||||||
|
|
||||||
|
|
||||||
## Sistemsko razhroščevanje
|
## Sistemsko razhroščevanje
|
||||||
|
|
||||||
- Za spletno razhroščevanje, sta priročna `curl` in `curl -I` ali pa njun ekvivalent `wget`, ali bolj moderen [`httpie`](https://github.com/jakubroztocil/httpie).
|
- Za spletno razhroščevanje, sta priročna `curl` in `curl -I` ali pa njun ekvivalent `wget`, ali bolj moderen [`httpie`](https://github.com/jkbrzt/httpie).
|
||||||
|
|
||||||
- Da izveste trenutni status diska/procesorja/omrežja, so na voljo klasična orodja `top`, (ali bolje `htop`), `iostat` in `iotop` . Uporabite `iostat -mxz 15` za osnovno statistiko CPU in podrobno na particijo statistiko diska in vpogled v uspešnost.
|
- Da izveste trenutni status diska/procesorja/omrežja, so na voljo klasična orodja `top`, (ali bolje `htop`), `iostat` in `iotop` . Uporabite `iostat -mxz 15` za osnovno statistiko CPU in podrobno na particijo statistiko diska in vpogled v uspešnost.
|
||||||
|
|
||||||
@ -276,7 +284,7 @@ Opombe:
|
|||||||
|
|
||||||
- Ko se razhroščuje, zakaj je šlo nekaj narobe v preteklosti, je lahko zelo uporaben `sar`. Prikazuje statistiko zgodovine na procesorju, spominu, omrežju itd.
|
- Ko se razhroščuje, zakaj je šlo nekaj narobe v preteklosti, je lahko zelo uporaben `sar`. Prikazuje statistiko zgodovine na procesorju, spominu, omrežju itd.
|
||||||
|
|
||||||
- Za globlje analize sistema in uspešnosti, poglejte `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)) in [`sysdig`](https://github.com/draios/sysdig).
|
- Za globlje analize sistema in uspešnosti, poglejte `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](https://en.wikipedia.org/wiki/Perf_(Linux)) in [`sysdig`](https://github.com/draios/sysdig).
|
||||||
|
|
||||||
- Preverite na katerem operacijskem sistemu ste z `uname` ali `uname -a` (splošne informacije Unix-a/jedra) ali `lsb_release -a` (informacije distribucuje Linux).
|
- Preverite na katerem operacijskem sistemu ste z `uname` ali `uname -a` (splošne informacije Unix-a/jedra) ali `lsb_release -a` (informacije distribucuje Linux).
|
||||||
|
|
||||||
@ -294,7 +302,7 @@ Nekaj primerov sestavljanja ukazov skupaj:
|
|||||||
cat a b b | sort | uniq -u > c # c is set difference a - b
|
cat a b b | sort | uniq -u > c # c is set difference a - b
|
||||||
```
|
```
|
||||||
|
|
||||||
- Uporabite `grep . *`, da vizualno preučite vse vsebine vseh datotek v direktoriju, npr. za direktorije napolnjene s konfiguracijskimi nastavitvami, kot so `/sys`, `/proc`, `/etc`.
|
- Uporabite `grep . *`, da hitro preučite vsebine vseh datotek v direktoriju (vsaka vrstica ima par z imenom datoteke) ali `head -100 *` (da iima vsaka datoteka glavo). To je lahko uporabno za direktorije napolnjene s konfiguracijskimi nastavitvami, kot so tiste v `/sys`, `/proc`, `/etc`.
|
||||||
|
|
||||||
|
|
||||||
- Povzetje vseh številk v tretjem stolpcu tekstovne datoteke (to je verjetno 3X hitrejše in 3X manj kode kot Python-ov ekvivalent):
|
- Povzetje vseh številk v tretjem stolpcu tekstovne datoteke (to je verjetno 3X hitrejše in 3X manj kode kot Python-ov ekvivalent):
|
||||||
@ -382,6 +390,8 @@ Nekaj primerov sestavljanja ukazov skupaj:
|
|||||||
|
|
||||||
- `time`: izvrši in da ukaz v čas
|
- `time`: izvrši in da ukaz v čas
|
||||||
|
|
||||||
|
- `timeout`: izvršite ukaz za določen čas in ustavite proces, ko se določen čas konča.
|
||||||
|
|
||||||
- `lockfile`: ustvari semaforno datoteko, ki je lahko odstranjena samo z `rm -f`
|
- `lockfile`: ustvari semaforno datoteko, ki je lahko odstranjena samo z `rm -f`
|
||||||
|
|
||||||
- `logrotate`: rotiranje, kompresiranje in pošiljanje dnevnikov po e-pošti.
|
- `logrotate`: rotiranje, kompresiranje in pošiljanje dnevnikov po e-pošti.
|
||||||
@ -396,7 +406,7 @@ Nekaj primerov sestavljanja ukazov skupaj:
|
|||||||
|
|
||||||
- `pv`: nadzira napredek podatkov skozi cev
|
- `pv`: nadzira napredek podatkov skozi cev
|
||||||
|
|
||||||
- `hd` in `bvi`: izvrže ali uredi binarne datoteke
|
- `hd`, `hexdump`, `xxd`, `biew` in `bvi`: izvrže ali uredi binarne datoteke
|
||||||
|
|
||||||
- `strings`: izvleče tekst iz binarnih datotek
|
- `strings`: izvleče tekst iz binarnih datotek
|
||||||
|
|
||||||
@ -493,10 +503,13 @@ To so elementi pomembni *samo* za MacOS.
|
|||||||
|
|
||||||
- Bodite pozorni, saj je MacOS osnovan na BSD Unix in mnogi ukazi (na primer `ps`, `ls`, `tail`, `awk`, `sed`) imajo mnoge subtilne različice iz Linux-a, na katerega je večinoma vplival System V-style Unix in GNU tools. Pogostokrat lahko poveste razliko tako, da opazite, da ima stran man naslov "BSD General Commands Manual." V nekaterih primerih se lahko namestijo tudi GNU različice (kot so `gawk` in `gsed` za GNU awk in sed). Če pišete skripte Bash za vse platforme, se izogibajte takim ukazom (na primer, z upoštevanjem Python ali `perl`) ali pazljivo testirajte.
|
- Bodite pozorni, saj je MacOS osnovan na BSD Unix in mnogi ukazi (na primer `ps`, `ls`, `tail`, `awk`, `sed`) imajo mnoge subtilne različice iz Linux-a, na katerega je večinoma vplival System V-style Unix in GNU tools. Pogostokrat lahko poveste razliko tako, da opazite, da ima stran man naslov "BSD General Commands Manual." V nekaterih primerih se lahko namestijo tudi GNU različice (kot so `gawk` in `gsed` za GNU awk in sed). Če pišete skripte Bash za vse platforme, se izogibajte takim ukazom (na primer, z upoštevanjem Python ali `perl`) ali pazljivo testirajte.
|
||||||
|
|
||||||
|
- Da dobite informacije o izdaji MacOS, uporabite `sw_vers`.
|
||||||
|
|
||||||
|
|
||||||
## Več virov
|
## Več virov
|
||||||
|
|
||||||
- [awesome-shell](https://github.com/alebcay/awesome-shell): urejan seznam orodij lupine in virov.
|
- [awesome-shell](https://github.com/alebcay/awesome-shell): urejan seznam orodij lupine in virov.
|
||||||
|
- [awesome-osx-command-line](https://github.com/herrbischoff/awesome-osx-command-line): Bolj poglobljen vodič za Mac OS ukazno vrstico.
|
||||||
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) za pisanje boljših skript lupine.
|
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) za pisanje boljših skript lupine.
|
||||||
- [shellcheck](https://github.com/koalaman/shellcheck): lupinska skripta orodja statične analize. V osnovi, lint za bash/sh/zsh.
|
- [shellcheck](https://github.com/koalaman/shellcheck): lupinska skripta orodja statične analize. V osnovi, lint za bash/sh/zsh.
|
||||||
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): Na žalost kompleksne podrobnosti, kako pravilno ravnati z imeni datotek v lupinskih skriptah.
|
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): Na žalost kompleksne podrobnosti, kako pravilno ravnati z imeni datotek v lupinskih skriptah.
|
||||||
|
344
README-uk.md
Normal file
344
README-uk.md
Normal file
@ -0,0 +1,344 @@
|
|||||||
|
[ Languages:
|
||||||
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
|
]
|
||||||
|
# Мистецтво командного рядка
|
||||||
|
|
||||||
|
[](https://gitter.im/jlevy/the-art-of-command-line?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
|
||||||
|
- [Опис](#Опис)
|
||||||
|
- [Основи](#Основи)
|
||||||
|
- [Щоденне використання](#Щоденне-використання)
|
||||||
|
- [Обробка файлів та інформації](#Обробка-файлів-та-інформації)
|
||||||
|
- [Дебаггінг](#Дебаггінг)
|
||||||
|
- [Одним рядком](#Одним-рядком)
|
||||||
|
- [Складно але корисно](#Складно-але-корисно)
|
||||||
|
- [MacOS only](#macos-only)
|
||||||
|
- [Інші джерела](#Інші-джерела)
|
||||||
|
- [Декламація](#Декламація)
|
||||||
|
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Використанню командного рядка часто не приділяють достатньої уваги. Про термінал говорять, як про щось містичне. Насправді, ці навики явно (і не явно) збільшує Вашу продуктивність в роботі. Даний документ є підбіркою заміток і порад, які я знайшов для себе корисними, працюючи з командним рядком в Linux. Деякі з них - прості й очевидні, але деякі - досить складні та призначені для вирішення конкретних завдань. Це невелика публікація, але якщо Ви вже все це знаєте, що тут написано, і можете згадати як це все використовувати - Ви знаєте багато!
|
||||||
|
|
||||||
|
Ця робота є результатом [багатьох авторів і перекладачів](AUTHORS.md).
|
||||||
|
Багато з цього [спочатку](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [появилось](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) на [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), почавши там, схоже, що варто розмістити і на Github, де знаходяться дуже талановиті люди і можуть допомогти. Якщо Ви замітили помилки (у всіх варіантах перекладу), будь ласка залиште опис [issue](https://github.com/jlevy/the-art-of-command-line/issues) або зробіть Pull requests (Звичайно перевіривши уже існуючі)
|
||||||
|
|
||||||
|
|
||||||
|
## Опис
|
||||||
|
|
||||||
|
Основне:
|
||||||
|
|
||||||
|
- Дана публікація призначена як для недосвідчених, так і для досвідчених користувачів. Цілі: *об'ємість* (зібрати всі важливі аспекти використання командного рядка), *практичність* (надати конкретні приклади для найчастіших задач) та *стислість* (не варто вдаватись у неочевидні речі, про які можна почитати в інших місцях).
|
||||||
|
- Цей документ написаний для користувачів Linux, із єдиним винятком - розділ "[MacOS only](#macos-only)". Все інше підходить для всі UNIX/MacOS системи (і навіть для Cygwin).
|
||||||
|
- Сфокусована на інтерактивному Bash, але багато речей також можуть бути використані в інших Шелах; і в застосовні до Bash-скриптів.
|
||||||
|
- Ця інструкція включає в себе стандартні Unix команди і ті, для яких потрібно встановлювати сторонні пакети. Вони настільки корисні, що варті того, щоб їх встановили.
|
||||||
|
|
||||||
|
Нотатки:
|
||||||
|
|
||||||
|
- Що б все вміщалось на одній сторінці, вся інформація вставлена прямо тут. Ви досить розумні для того, щоб самостійно вивчити питання більш детально в іншому місці. Використовуйте `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (залежно від вашої системи управління пакетами) для установки нових програм.
|
||||||
|
- На [Explainshell](http://explainshell.com/) можна знайти просте і докладне пояснення того, що таке команди, їх опції, пайпи(pipes(*|*)) і т.д.
|
||||||
|
|
||||||
|
|
||||||
|
##Основи
|
||||||
|
|
||||||
|
- Вивчіть основи Bash. Просто візьміть і наберіть у командному рядку `man bash` в терміналі і хоча б перегляньте; він досить просто читається і він не дуже великий. Інші шелли теж можуть бути хороші, але Bash - потужна програма, і Bash завжди під рукою (використання *виключно* zsh, fish і т.д., які напевно круто виглядають на Вашому лептопі і ні в чому Вас не обмежують, наприклад Ви не зможете використовувати ці можливості Шеллу на вже існуючому сервері).
|
||||||
|
- Вивчіть як використовувати хоча б один консольний редактор тексту. Найкраще Vim (`vi`), адже у нього немає конкурентів, коли вам потрібно швиденько щось підправити (навіть якщо Ви постійно сидите у Emacs чи, якомусь важкому IDE або на модному хіпстерському редакторі.
|
||||||
|
- Знайте, як читати документацію через `man` (`man man`; `man` у кутах документа в дужках додає номер, наприклад 1 - для звичайних команд, 5 - для файлів, 8 - для адміністративних команд). Шукайте інформацію через `apropos`, і пам'ятайте, що деякі команди - не виконувані(executables), а вбудовані команди Bash, і допомогу по них можна отримати через команду `help` і `help -d`.
|
||||||
|
- Можна перенаправляти введення та виведення через `>` і `<` і пайпи `|`. Пам'ятайте, що `>` - переписує вихідний файл, а `>>` додає до нього. Дізнайтеся побільше про stdout і stderr.
|
||||||
|
- Дізнайтеся побільше про `*` (а також `?` і `[`...`]`), кавички, а також різницю між подвійними `"` і одинарними `'` кавичками.
|
||||||
|
- Знайте як працювати із процесами в Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, і т.д.
|
||||||
|
- Знайте `ssh` та основи беспарольної аутентифікації через `ssh-agent`, `ssh-add`, і т.д.
|
||||||
|
- Основи роботи з файлами: `ls` і `ls -l` (зокрема, дізнайтеся, що значить кожен стовпець в `ls -l`), `less`, `head`,` tail` і `tail -f` (або навіть краще - `less + F`), `ln` і `ln -s` (дізнайтеся різницю між символьними посиланнями і жорсткими посиланнями, і чому жорсткі посилання краще), `chown`, `chmod`, `du` (для отримання швидкої інформації по використанню диска: `du -hk *`). Для менеджменту файлової системи, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`.
|
||||||
|
- Основи роботи з мережею: `ip` або` ifconfig`, `dig`.
|
||||||
|
- Добре знайте регулярні вирази і різні опції для `grep`/`egrep`. Такі опції як `-i`, `-o`, `-A`, та `-B` варто знати.
|
||||||
|
- Навчіться використовувати системами управління пакетами `apt-get`, `yum`, `dnf` та `pacman` (залежно від дистрибутива). Знайте як шукати і встановлювати пакети і обов'язково майте встановленим `pip` для установки командних утиліт, написаних на Python (деякі з тих команд, що ви знайдете нижче, найлегше встановити через` pip`).
|
||||||
|
|
||||||
|
|
||||||
|
##Щоденне-використання
|
||||||
|
|
||||||
|
- Використовуйте клавішу таб в Bash для автодоповнення аргументів до командам та **ctrl-r** для пошуку по історії командного рядка.
|
||||||
|
- Використовуйте **ctrl-w** в Bash для того, щоб видалити останнє слово в команді; **ctrl-u** для того, щоб видалити команду повністю. Використовуйте **alt-b** і **alt-f** для того, щоб переміщатись між словами у команді, **ctrl-k** для того, щоб перейти в кінця рядка, **ctrl-l** для того, щоб очистити екран. Гляньте на `man readline` щоб дізнатися про всі шорткати Bash. Їх багато! Наприклад, **alt-.** переміщається між попередніми аргументам команди, а **alt-*** максимально розширює аргументи.
|
||||||
|
- Якщо Вам подобаються шорткати vim, виконайте `set -o vi` (`set -o emacs` що б повернути налаштування).
|
||||||
|
- Для редагування довгих команд після налаштування вашого консольного редактора (наприклад `export EDITOR=vim`), **ctrl-x** **ctrl-e** відкриє поточну команду в редакторі для багаторядкового редагування команди. Або у vi стилі, **escape-v**.
|
||||||
|
- Для того, щоб переглянути історію, введіть `history`. Також існує безліч абревіатур, наприклад `! $` - Останній аргумент, `!!` - остання команда, хоча ці абревіатури часто заміняються шорткати **ctrl-r** та **alt-.**.
|
||||||
|
- Для того, щоб стрибнути до останньої робочої директорії, використовуйте `cd -`
|
||||||
|
- Якщо Ви написали команду наполовину і раптом передумали, натисніть **alt-#** для того, щоб додати `#` на початок команди, та відправте команду як коментар. Потім ви зможете повернутися до неї через історію команд.
|
||||||
|
- Використовуйти `xargs` (або` parallel`). Це дуже корисно. Зверніть увагу, що Ви можете контролювати кількість команд на кожен рядок (`-L`) також паралельність (`-P`). Якщо Ви не впевнені, що робите щось правильно, почніть з `xargs echo`. Також `-I{}` - корисно. Приклади:
|
||||||
|
```bash
|
||||||
|
find . -name '*.py' | xargs grep some_function
|
||||||
|
cat hosts | xargs -I{} ssh root@{} hostname
|
||||||
|
```
|
||||||
|
- `pstree -p` - допоможе побачити дерево процесів.
|
||||||
|
- Використовуйте `pgrep` і `pkill` для того, щоб знаходити або слати сигнали до процесів по імені (`-f` корисна опція).
|
||||||
|
- Знайте різні сигнали, які можна слати процесам. Наприклад, щоб призупинити процес, використовуйте `kill -STOP [pid]`. Для повного списку подивіться `man 7 signal`.
|
||||||
|
- Використовуйте `nohup` або` disown`, якщо ви хочете запустити фоновий процес що б він постійн виконувався у фоні.
|
||||||
|
- Дізнайтеся, які процеси слухають порти через `netstat -lntp` або `ss -plat` (для TCP; додайте `-u` для UDP).
|
||||||
|
- Зверніть увагу на `lsof` щоб подивитися відкриті сокети і файли.
|
||||||
|
- Команда `uptime` or `w` показує як довго працює система.
|
||||||
|
- Використовуйте `alias`, щоб створити скорочення для часто використовуємих команд. Наприклад, `alias ll='ls -latr'` створить нове скорочення(alias) `ll`.
|
||||||
|
- У Bash скриптах використовуйте `set -x` (або `set -v`) щоб дебажити вивід. Використовуйте строгий(strict) режим скрізь, де це можливо. Використовуйте `set -e` для того, щоб припиняти виконання при помилках (не нульовий вихідний код). Використовуйте `set -u` що б визначити невстановленні змінні. Використовуйте `set -o pipefail` щоб при помилках невикористовувати пайпи(вертикальна риска). Для більш складних скриптів також використовуйте `trap` на EXIT or ERR.
|
||||||
|
Корисний звичка почати використовувати настипний скрипт, який допоможе виявити і перервати на загальних помилоках і вивести повідомлення:
|
||||||
|
```bash
|
||||||
|
set -euo pipefail
|
||||||
|
trap "echo 'error: Script failed: see failed command above'" ERR
|
||||||
|
```
|
||||||
|
- У Bash-скриптах підоболочки(subshells) - зручний спосіб групувати команди. Один із найпоширеніших прикладів - тимчасово пересунутися в іншу робочу директорію:
|
||||||
|
```bash
|
||||||
|
# Do something in current dir
|
||||||
|
(cd / some / other / dir && other-command)
|
||||||
|
# Continue in original dir
|
||||||
|
```
|
||||||
|
- У Bash багато типів простору змінних. Перевірити, чи існує змінна - `${name:? Error message}`. Наприклад, якщо Bash-скрипту потрібен всього один аргумент, просто напишіть `input_file=${1:?usage: $0 input_file}`. Арифметична область видимості: `i=$(( (i + 1) % 5 ))`. Послідовності: `{1..10}`. Обрізка рядків: `${var%suffix}` і `${var#prefix}`. Наприклад, якщо `var=foo.pdf` тоді `echo ${var%.pdf}.txt` виведе `foo.txt`.
|
||||||
|
- Фігурні скобки, використовуючи `{`...`}` може зменшити необхідність повторно вводити той самий текст і автоматизувати. Це корисно в такому прикладі як `mv foo.{txt,pdf} some-dir` (який пересуває обидва файла), `cp somefile{,.bak}` (який розширюється у `cp somefile somefile.bak`) або `mkdir -p test-{a,b,c}/subtest-{1,2,3}` (яка розширює всі можливі комбінації і створює дерево деректорій).
|
||||||
|
- Вивід будь-якої команди можна обробити як файл наступним чином `<(some command)`. Наприклад, порівняння локального файлу `/etc/hosts з віддаленим:
|
||||||
|
```sh
|
||||||
|
diff /etc/hosts <(ssh somehost cat /etc/hosts)
|
||||||
|
```
|
||||||
|
- Знайте про *heredoc* -сінтаксис в Bash: `cat << EOF ...`.
|
||||||
|
- У Bash перенаправляйте стандартні потоки виводу(output) та помилок, ось так: `some-command >logfile 2>&1`. Найчастіше, для того, щоб переконається, що команда не залишить відкритим файл, прив'язавши його до відкритого терміналу, вважається хорошою практикою додавати `</dev/null`.
|
||||||
|
- Використовуйте `man ascii` щоб отримати таблицю ASCII символів із шіснадцядковими і десятковими значеннями. Для інших основних кодувань користуйтесь: `man unicode`,` man utf-8` і `man latin1`.
|
||||||
|
- Використовуйте `screen` або [`tmux`](https://tmux.github.io/) для того, щоб мати кілька екранів в одному терміналі. Це особливо корисно в ssh сесії що б приєднатись чи відєднатись до сесії. `byobu` розширити функціонал screen або tmux надавши більше інформації і полегшити керування. Більш мінімалістичною альтернативою для цього - `dtach`.
|
||||||
|
- У SSH корисно знати як зробити port tunnel з опціями `-L` і` -D` (іноді `-R`) це корисно наприклад для того, щоб отримати доступ до сайту із віддаленого сервера.
|
||||||
|
- Ще може бути корисно зробити декілька оптимізацій у конфігурації вашого SSH, наприклад у файлі `~/.ssh/config` містить налаштування, які допомагають уникати втрачених підключень в деяких мережевих оточеннях, використати стиснення (яке корисне при використанні scp при повільному підключенні) і збільште кількість каналів до одного сервера через цей конфіг, ось так:
|
||||||
|
```
|
||||||
|
TCPKeepAlive=yes
|
||||||
|
ServerAliveInterval=15
|
||||||
|
ServerAliveCountMax=6
|
||||||
|
Compression=yes
|
||||||
|
ControlMaster auto
|
||||||
|
ControlPath /tmp/%r@%h:%p
|
||||||
|
ControlPersist yes
|
||||||
|
```
|
||||||
|
- Деякі із інших налаштування SSH можуть сильно вплинути на безпеку і повинні мінятися обережно, наприклад, для конкретної підмережі або конкретної машини або в домашніх мережах: `StrictHostKeyChecking=no`, `ForwardAgent=yes`
|
||||||
|
- Розглянемо [`mosh`](https://mosh.mit.edu/) як альтернатива ssh який використовує UDP, уникаючи розривів підключеня (вимагає установки на стороні сервера).
|
||||||
|
- Щоб отримати права доступу до файлу в вісімковому вигляді, що є корисно для конфігурації систем але не можна отримати з допомогою команди `ls`, можна використовувати щось схоже на це:
|
||||||
|
```sh
|
||||||
|
stat -c '%A %a %n' /etc/timezone
|
||||||
|
```
|
||||||
|
- Для інтерактивного виділення результатів інших команд використовуйте [`percol`](https://github.com/mooz/percol) або [`fzf`](https://github.com/junegunn/fzf).
|
||||||
|
- Для роботи з файлами, список яких дала інша команда (наприклад `git`), використовуйте `fpp` ([PathPicker](https://github.com/facebook/PathPicker)).
|
||||||
|
- Щоб швидко підняти веб-сервер в поточній директорії (і піддерикторіях), який доступний для всіх у вашій мережі, використовуйте:
|
||||||
|
`python -m SimpleHTTPServer 7777` (на прту 7777 і для Python 2) або `python -m http.server 7777` (на прту 7777 і для Python 3).
|
||||||
|
- Щоб виконати команду з привілеями, використовуйте `sudo` (для root) і` sudo -u` (для іншого користувача). Використовуйте `su` або` sudo bash`, щоб запустити шелл від імені цього користувача. Використовуйте `su -`, щоб симулювати свіжий вхід під root або gsl іншим користувачем.
|
||||||
|
|
||||||
|
|
||||||
|
##Обробка-файлів-та-інформації
|
||||||
|
|
||||||
|
- Для того, щоб знайти файл в поточній директорії, зробіть `find. -iname '*something*'`. Для того, щоб шукати файл по всій системі, використовуйте `locate something` (але не забувайте, що `updatedb` міг ще не проіндексувати нещодавно створені файли).
|
||||||
|
- Для пошуку по вмісту або фалах (більш детально зробити пошук допоможе `grep -r`) використовуйте [`ag`](https://github.com/ggreer/the_silver_searcher).
|
||||||
|
- Для конвертації HTML в текст: `lynx -dump -stdin`
|
||||||
|
- Для конвертації різних типів розмітки (HTML, Markdown та ін.) попроробуйте [`pandoc`](http://pandoc.org/).
|
||||||
|
- Якщо потрібно працювати з XML, є стара, але хороша утиліта - `xmlstarlet`.
|
||||||
|
- Для роботи з JSON використовуйте [`jq`](http://stedolan.github.io/jq/).
|
||||||
|
- Для YAML використовуйте [`shyaml`](https://github.com/0k/shyaml).
|
||||||
|
- Для Excel і CSV файлів [csvkit](https://github.com/onyxfish/csvkit) надає `in2csv`,` csvcut`, `csvjoin`,` csvgrep` і т.д.
|
||||||
|
- Для Amazon S3 [`s3cmd`](https://github.com/s3tools/s3cmd) є зручним і [`s4cmd`](https://github.com/bloomreach/s4cmd) є швидшим. Для решти сервісів Амазону використовуйте стандартний [`aws`](https://github.com/aws/aws-cli) і удосконалений [`saws`](https://github.com/donnemartin/saws).
|
||||||
|
- Знайте про `sort` і `uniq`, включаючи опції `-u` і `-d`, дивіться приклади нижче. Ще спробуйте `comm`.
|
||||||
|
- Знайте про `cut`, `paste`, і `join` для роботи з текстовими файлами. Багато людей використовують `cut`, забувши про `join`.
|
||||||
|
- Знайте про `wc`: для підрахунку нових рядків (`-l`), символів (`-m`), слів (`-w`) і для байтового підрахунку (`-c`).
|
||||||
|
- Знайте про `tee` для копіювання в файл з stdin і stdout, щось типу `ls -al | tee file.txt`.
|
||||||
|
- Не забувайте, що Ваша місце знаходження (локаль) впливає на багато команд, включаючи порядок сортування, порівняння і продуктивність. Багато дистрибутиви Linux автоматично виставляють `LANG` або будь-яку іншу змінну в підходящу для Вашого регіону. Через це результати функцій сортування можуть працювати непередбачувано. Знайте що `i18n` можуть значно знизити продуктивність сортувань. У деяких випадках можна повністю цього уникати (за винятком рідкісних випадків), сортуючи традиційно побайтово, використовуйте `export LC_ALL = C`.
|
||||||
|
- Знайте основи `awk` і `sed` для простих маніпуляцій з даними. Наприклад, щоб отримати суму всіх чисел, які знаходяться в третій колонці текстового файлу, можна використати `awk '{ x += $3 } END { print x }'`. Швидше за все, це вийде в рази 3 швидше і рази в 3 простіше, ніж робити це в Пітоні.
|
||||||
|
- Щоб замінити всі знаходження підрядка в одному або декількох файлах:
|
||||||
|
```sh
|
||||||
|
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
||||||
|
```
|
||||||
|
- Щоб перейменувати відразу багато файлів за шаблоном, використовуйте `rename`. Для складних перейменувань може допомогти [`repren`](https://github.com/jlevy/repren):
|
||||||
|
```sh
|
||||||
|
# Recover backup files foo.bak -> foo:
|
||||||
|
rename 's/\.bak$//' *.bak
|
||||||
|
# Full rename of filenames, directories, and contents foo -> bar:
|
||||||
|
repren --full --preserve-case --from foo --to bar .
|
||||||
|
```
|
||||||
|
- Як говорить man сторінка, `rsync` дійсно є швидким і універсальним інструментом копіювання файлів, для синхронізації між машинами, але в рівній мірі корисні на локальному рівні. Також [швидке рішення](https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html) що б видалити велику кількість файлів:
|
||||||
|
```sh
|
||||||
|
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
|
||||||
|
```
|
||||||
|
- Використовуйте `shuf`, щоб перемішати або вибрати випадкові рядки з файлу.
|
||||||
|
- Знайте опції для команди `sort`. Для чисел використовуйте `-n` або `-h`, для роботи з числами (наприклад `du -h`). Знайте як працюють ключі (`-t` і `-k`). Зокрема, не забувайте, що вам потрібно писати `-k1,1` для того, щоб впорядкувати тільки перше поле; `-k1` - це означає сортування враховуючи цілий рядок. Може бути корисною (`sort -s`). Наприклад для того, щоб відсортувати найважливіше по другому полю, а другорядне по першому, можна використовувати `sort -k1,1 | sort -s -k2,2`.
|
||||||
|
- Якщо вам коли-небудь доведеться написати код символу табуляції в терміналі, наприклад, для сортування за табуляції з прапором -t, використовуйте скорочення **ctrl-v** **[Tab]** або напишіть `$'\t'`. Останнє краще, тому що його можна скопіювати/вставити.
|
||||||
|
- Стандартні інструменти для виправлення вихідного коду це `diff` і` patch`. Також зверніть увагу на `diffstat` для перегляду статистики diff і `sdiff` для крок за кроком diff. Запамятайте `diff -r` працює рекурсивно по всій директорії. Використовуйте `diff -r tree1 tree2 | diffstat` для повного зведення змін. Використовуйте `vimdiff` порівняти і редагувати файли.
|
||||||
|
- Для бінарних файлів використовуйте `hd`, `hexdump` або `xxd` для простих hex-дампом, і` bvi` або `biew` для зміни бінарників.
|
||||||
|
- Також для бінарних файлів, `strings` (plus `grep`, etc.) дозволить Вам знайти біти тексту.
|
||||||
|
- Щоб подивитися різницю в бінарниках (дельта-кодування): `xdelta3`.
|
||||||
|
- Для конвертування кодувань використовуйте `iconv`. Для більш складних завдань - `uconv`, він підтримує деякі складні фічі Юникода. Наприклад, ця команда переводить рядки з файлу в нижній регістр і прибирає наголоси (наприклад в іспанській мові)
|
||||||
|
```sh
|
||||||
|
uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC; ' < input.txt > output.txt
|
||||||
|
```
|
||||||
|
- Для того, щоб розбити файл на шматки, використовуйте `split` (розбиває на шматки за розміром), або `csplit` (за шаблоном або по регулярному виразу).
|
||||||
|
- Для дати і часу використовуйте `dateadd`, `datediff`, `strptime` ще можете знайти на [`dateutils`](http://www.fresse.org/dateutils).
|
||||||
|
- Використовуйте `zless`,` zmore`, `zcat`, і `zgrep` для роботи зі стиснутими файлами.
|
||||||
|
|
||||||
|
|
||||||
|
##Дебаггінг
|
||||||
|
|
||||||
|
- Дле веб-дебаггінга використовуйте `curl` і `curl -I`, або альтернативу - `wget` або [`httpie`](https://github.com/jakubroztocil/httpie).
|
||||||
|
- Щоб отримати інформацію про диск/CPU/мережі використовуйте `iostat`,` netstat`, `top` (краще `htop`) і `dstat`. Використовуйте `iostat -mxz 15` для отримання основної інформації CPU.
|
||||||
|
- Для інформації про мережу використовуйте `netstat` і `ss`.
|
||||||
|
- Для більш детальної інформації використовуйте [`glances`](https://github.com/nicolargo/glances). Ця програма показує відразу кілька різних статистик в одному вікні терміналу. Корисно, коли стежите за відразу декількома системами.
|
||||||
|
- Для того, щоб стежити за пам'яттю вокористовуйте `free` і `vmstat`. Зокрема, не забувайте, що значення кешування ("cached" value) - Це пам'ять, яку тримає ядро і ці значення є частиною `free`.
|
||||||
|
- Використовуйте `mtr` для кращого трасування(простежити маршрут), щоб знаходити проблеми мережі.
|
||||||
|
- Для того, щоб дізнатися, чому диск повністю забитий, використовуйте `ncdu`, це зберігає час у порівнянні з тим же `du -sh *`.
|
||||||
|
- Для того, щоб дізнатися, який сокет або процес використовує інтернет, використовуйте `iftop` або `nethogs`.
|
||||||
|
- додаток `ab` який поставляється разом з apache, корисний для швидкої і поверхневої перевірки продуктивності веб-сервера. Для більш серйозного лоад-тестінгу використовуйте `siege`.
|
||||||
|
- Для більш серйозного дебаггінга мережі використовуйте `wireshark`,` tshark`, і `ngrep`.
|
||||||
|
- Знайте про `strace` і` ltrace`. Ці команди можуть бути корисні, якщо програма падає або висить, і ви не знаєте чому або якщо ви хочете протестувати продуктивність програми. Не забувайте про можливість дебаггінга (`-c`) і можливість причепитися до процесу по pid (` -p`).
|
||||||
|
- `ldd` для перевірки системних бібліотек.
|
||||||
|
- Знайте як причепитися до працюючого процесу через `gdb` і отримати трасування стека.
|
||||||
|
- Використовуйте `/proc`. Іноді він неймовірно корисний для налагодження запущених програм. Приклади: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps` (де `xxx` id or pid процесу).
|
||||||
|
- Коли дебажите щось, що зламалося в минулому, використовуйте `sar` буває дуже корисно. Показує історію та статистику CPU, пам'яті, мережі і т.д.
|
||||||
|
- Для аналізу більш складних систем і продуктивності використовуйте `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/ Perf_(Linux)), і [`sysdig`](https://github.com/draios/sysdig).
|
||||||
|
- Дізнайтеся, яка у вас операційна система, через `uname` або `uname -a` або `lsb_release -a`.
|
||||||
|
- Використовуйте `dmesg`, коли щось відбувається зовсім дивне (це може бути проблеми із залізом або драйверами).
|
||||||
|
|
||||||
|
|
||||||
|
##Одним-рядком
|
||||||
|
|
||||||
|
Кілька прикладів склеювання команд:
|
||||||
|
- Це досить круто, що можна знайти множинні перетину файлів, з'єднати відсортовані файли і подивитися різницю в декількох файлів через `sort` /`uniq`. Це швидкий підхід і працює на файлах будь-якого розміру (включаючи багатогігабайтними файли). (Сортування не обмежена пам'яттю, але можливо вам доведеться додати `-T`, якщо `/tmp` знаходиться на невеликому логічному диску). Ще подивіться те, що було сказано вище про `LC_ALL`. Прапор сортування `-u` не використовується нижче, щоб було зрозуміліше:
|
||||||
|
```sh
|
||||||
|
cat a b | sort | uniq > c # c is a union b
|
||||||
|
cat a b | sort | uniq -d > c # c is a intersect b
|
||||||
|
cat a b b | sort | uniq -u > c # c is set difference a - b
|
||||||
|
```
|
||||||
|
- Використовуйте `grep. *` для того, щоб подивитися вміст всіх файлів в директорії. Це може бути корисно для директорій заповнених конфігураціями як ці в `/sys`,` / proc`, `/ etc`.
|
||||||
|
- Просумувати всі числа, які знаходяться в третій колонці текстового файлу (це в 3 рази швидше і 3 рази простіше, ніж робити це в Пітоні):
|
||||||
|
```sh
|
||||||
|
awk '{ x += $3 } END { print x }' myfile
|
||||||
|
```
|
||||||
|
- Якщо вам потрібно подивитися розміри/дати файлів в дереві, це як рекурсивний `ls -l` але легше прочитати це `ls -lR`:
|
||||||
|
```sh
|
||||||
|
find . -type f -ls
|
||||||
|
```
|
||||||
|
- Скажемо що у нас є якийсь текстовий файл, наприклад лог веб сервера і на якихось рядках з'являється значення, рядки з яким нам цікаві. Наприклад, `acct_id`. Давайте підрахуємо, скільки таких запитів в нашому логе:
|
||||||
|
```sh
|
||||||
|
cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn
|
||||||
|
```
|
||||||
|
- Використовуйте `xargs` (або` parallel`). Зверніть увагу, що Ви можете контролювати кількість команд на кожен рядок, а так само паралельність. Якщо Ви не впевнені, що робите правильно, почніть з `xargs echo`. Ще `-I {}` - корисна штука. Приклади:
|
||||||
|
```sh
|
||||||
|
find. -name '* .py' | xargs grep some_function
|
||||||
|
cat hosts | xargs -I {} ssh root @ {} hostname
|
||||||
|
```
|
||||||
|
- Запустіть цю функцію, щоб отримати випадкову вибірку із цього документа:
|
||||||
|
```sh
|
||||||
|
function taocl() {
|
||||||
|
curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md |
|
||||||
|
pandoc -f markdown -t html |
|
||||||
|
xmlstarlet fo --html --dropdtd |
|
||||||
|
xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" |
|
||||||
|
xmlstarlet unesc | fmt -80
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
##Складно-але-корисно
|
||||||
|
|
||||||
|
- `expr`: для виконання арифметичних і булевих операцій, а також регулярних виразів
|
||||||
|
- `m4`: простий макро-процесор
|
||||||
|
- `yes`: безкінечно виводить рядок
|
||||||
|
- `cal`: хороший календар
|
||||||
|
- `env`: виводить змінні середовища (корисно в Bash-скриптах)
|
||||||
|
- `printenv`: показати змінні оточення (корисно в скриптах або дебаггінгу)
|
||||||
|
- `look`: знайде англійські слова (або рядки у файлі) які починаються із рядках
|
||||||
|
- `cut`, `paste` і` join`: маніпуляції з даними
|
||||||
|
- `fmt`: форматування параграфів у тексті
|
||||||
|
- `pr`: відформатовує текст в сторінки/колонки
|
||||||
|
- `fold`: (обернути) обмежити довжину рядків у файлі
|
||||||
|
- `column`: форматувати текст в колонки або таблиці
|
||||||
|
- `expand` і` unexpand`: конвертація між табами і пробілами
|
||||||
|
- `nl`: додає номери до рядків
|
||||||
|
- `seq`: вивести послідовність чисел
|
||||||
|
- `bc`: калькулятор
|
||||||
|
- `factor`: піднести число в степінь
|
||||||
|
- [`gpg`](https://gnupg.org/): зашифрувати і підписати файли
|
||||||
|
- `toe`: таблиця терміналів terminfo з описом
|
||||||
|
- `nc`: дебаггінг мережі і передачі даних
|
||||||
|
- `socat`: перемикач сокетів і перенаправлення tcp-портів (схоже на `netcat`)
|
||||||
|
- [`slurm`](https://github.com/mattthias/slurm): візуалізація трафіку мережі
|
||||||
|
- `dd`: перенесення інформації між файлами фбо пристроями
|
||||||
|
- `file`: визначає тип файлу
|
||||||
|
- `tree`: показує директорії і піддиректорії у вигляді дерева, як `ls`, але рекурсивно
|
||||||
|
- `stat`: інформація про файл
|
||||||
|
- `time`: execute and time a commands
|
||||||
|
- `timeout`: зупиняє коменду після того як завершиться вказаний чав в аргументі
|
||||||
|
- `lockfile`: створює позначку в файлі який може бути видаленим тільки через команду `rm -f`
|
||||||
|
- `logrotate`: змінити, зжати і відправити логи.
|
||||||
|
- `watch`: запустити команду повторно, показуючи результати і/або виділення змін
|
||||||
|
- `tac`: вивести файли посимвольно навпаки ("тівирп")
|
||||||
|
- `shuf`: випадкова вибірка рядків з файлу
|
||||||
|
- `comm`: порядково порівняти відсортовані файли
|
||||||
|
- `pv`: моніторинг прогресу проходження інформації через пайп
|
||||||
|
- `hd`, `hexdump`, `xxd`, `biew` і `bvi`: дамп і редагування бінарних файлів
|
||||||
|
- `strings`: витягнути текст із бінарних файлів
|
||||||
|
- `tr`: маніпуляція з char (символьним типом)
|
||||||
|
- `iconv` або `uconv`: конвертація кодувань
|
||||||
|
- `split` і `csplit`: розбити файли
|
||||||
|
- `sponge`: прочитати весь інпут перед тим, як його записати. Корисно, коли читаєш з того ж файлу, куди записуєш. Наприклад, ось так: `grep -v something some-file | sponge some-file`
|
||||||
|
- `units`: конвертер. Метри в кілометри, версти в п'яді (дивіться `/usr/share/units/definitions.units`)
|
||||||
|
- `apg`: генерація паролів
|
||||||
|
- `7z`: архіватор з високим ступенем стиснення
|
||||||
|
- `ldd`: показує залежності програми від системних бібліотек
|
||||||
|
- `nm`: symbols from object files
|
||||||
|
- `ab`: бенчмаркінг веб-серверів
|
||||||
|
- `strace`: дебагінг системних викликів
|
||||||
|
- `mtr`: трасування для дебаггінга мережі
|
||||||
|
- `cssh`: графічний конкурент Shel
|
||||||
|
- `rsync`: синхронізація файлів і папок через SSH або на локальній файловій системі
|
||||||
|
- `wireshark` і `tshark`: перехоплення пакетів і дебагінг мережі
|
||||||
|
- `ngrep`: grep для шару мережі (network layer)
|
||||||
|
- `host` і `dig`: пошук DNS
|
||||||
|
- `lsof`: процесинг дескрипторів і інформація по сокетах
|
||||||
|
- `dstat`: корисна статистика ОС
|
||||||
|
- [`glances`](https://github.com/nicolargo/glances): високорівнева статистика з багатьма підсистемам
|
||||||
|
- `iostat`: статистика використання жорсткого диска
|
||||||
|
- `mpstat`: статистика використання CPU
|
||||||
|
- `vmstat`: статистика використання оперативної пам'яті
|
||||||
|
- `htop`: вдосконалена версія `top`
|
||||||
|
- `last`: історія входів у систему
|
||||||
|
- `w`: хто є залогіненим
|
||||||
|
- `id`: інформація про користувача/групу
|
||||||
|
- `sar`: historic system stats
|
||||||
|
- `iftop` або` nethogs`: використання мережі конкретним сокетом або процесом
|
||||||
|
- `ss`: статистика сокетів
|
||||||
|
- `dmesg`: помилки завантаження і помилки системи
|
||||||
|
- `sysctl`: перегляду і налаштування параметрів ядра Linux коли воно запущене
|
||||||
|
- `hdparm`: маніпуляція/налаштування SATA/ATA диску
|
||||||
|
- `lsb_release`: інформація про дистрибутив Linux
|
||||||
|
- `lsblk`: cписок блокових пристроїв комп'ютера: дерево ваших дисків і логічних дисків
|
||||||
|
- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: інформація про апаратне забезпечення, включає CPU, BIOS, RAID, графічну карту і т.д.
|
||||||
|
- `lsmod` і `modinfo`: показує список і детальну інформацію модулів ядра.
|
||||||
|
- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful"
|
||||||
|
|
||||||
|
|
||||||
|
##Macos-only
|
||||||
|
|
||||||
|
Деякі речі, які підходять *тільки* для Мака.
|
||||||
|
|
||||||
|
- Система управління пакетами - `brew` (Homebrew) і `port` (MacPorts) можуть бути використані для того, щоб встановити більшість програм, згаданих у цьому документі.
|
||||||
|
- Копіюйте вивід будь-якої консольної команди до графічної за допомогою `pbcopy` і вставляйте вивід за допомогою `pbpaste`.
|
||||||
|
- Щоб відкрити файл або десктопну програму, використовуйте `open` або `open -a /Applications/Whatever.app`.
|
||||||
|
- Spotlight: Шукає файли в консолі, через `mdfind`, і дивиться метадані (наприклад EXIF інформацію із фотографії) із `mdls`.
|
||||||
|
- Не забувайте, що MacOS створений на основі BSD Unix і багато команд (наприклад `ps`, `ls`, `tail`, `awk`, `sed`) мають невеликі відмінності від лінуксових. Це обумовлено впливом `UNIX System V` і `GNU Tools`. Різницю можна помітити, побачивши заголовок "BSD General Commands Manual." Інколи на MacOS можна поставити GNU-версії програм, наприклад `gawk` і `gsed`. Коли пишете кросплатформені Bash-скрипти, намагайтеся уникати використовувати команди, які можуть відрізнятися (наприклад, краще використовуйте Python або `perl`), або ретельно все перевіряйте.
|
||||||
|
|
||||||
|
|
||||||
|
##Інші-джерела
|
||||||
|
|
||||||
|
- [awesome-shell](https://github.com/alebcay/awesome-shell): Розширює Shell.
|
||||||
|
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) щоб краще писати Shell скрипти.
|
||||||
|
- [shellcheck](https://github.com/koalaman/shellcheck): A shell script static analysis tool. Essentially, lint for bash/sh/zsh.
|
||||||
|
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): The sadly complex minutiae on how to handle filenames correctly in shell scripts.
|
||||||
|
|
||||||
|
|
||||||
|
##Декламація
|
||||||
|
|
||||||
|
За невеликим винятком, весь код написаний так, щоб інші його змогли прочитати.
|
||||||
|
Той факт, що щось може бути написано на Bash, зовсім не означає, що воно має бути на ньому написано. ;)
|
||||||
|
|
||||||
|
|
||||||
|
## Лицензія
|
||||||
|
|
||||||
|
[](http://creativecommons.org/licenses/by-sa/4.0/)
|
||||||
|
|
||||||
|
Ця работа і переклад на Українську мову розповсюджується за ліцензією [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/).
|
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -194,7 +194,7 @@
|
|||||||
|
|
||||||
- 了解如何使用 `tee` 将标准输入复制到文件甚至标准输出,例如 `ls -al | tee file.txt`。
|
- 了解如何使用 `tee` 将标准输入复制到文件甚至标准输出,例如 `ls -al | tee file.txt`。
|
||||||
|
|
||||||
- 了解语言环境对许多命令行工具的微妙影响,包括排序的顺序和性能。大多数 Linux 的安装过程会将 `LANG` 或其他有关的变量设置为符合本地的设置。意识到当你改变语言环境时,排序的结果可能会改变。明白国际化可能会时 sort 或其他命令运行效率下降*许多倍*。某些情况下(例如集合运算)你可以放心的使用 `export LC_ALL=C` 来忽略掉国际化并使用基于字节的顺序。
|
- 了解语言环境对许多命令行工具的微妙影响,包括排序的顺序和性能。大多数 Linux 的安装过程会将 `LANG` 或其他有关的变量设置为符合本地的设置。意识到当你改变语言环境时,排序的结果可能会改变。明白国际化可能会使 sort 或其他命令运行效率下降*许多倍*。某些情况下(例如集合运算)你可以放心的使用 `export LC_ALL=C` 来忽略掉国际化并使用基于字节的顺序。
|
||||||
|
|
||||||
- 了解 `awk` 和 `sed` 关于数据的简单处理的用法。例如,将文本文件中第三列的所有数字求和:`awk '{ x += $3 } END { print x }'`. 这可能比同等作用的 Python 代码快三倍且代码量少三倍。
|
- 了解 `awk` 和 `sed` 关于数据的简单处理的用法。例如,将文本文件中第三列的所有数字求和:`awk '{ x += $3 } END { print x }'`. 这可能比同等作用的 Python 代码快三倍且代码量少三倍。
|
||||||
|
|
||||||
|
26
README.md
26
README.md
@ -1,5 +1,5 @@
|
|||||||
[ Languages:
|
[ Languages:
|
||||||
[English](README.md), [Español](README-es.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [中文](README-zh.md)
|
[English](README.md), [Español](README-es.md), [Italiano](README-it.md), [日本語](README-ja.md), [한국어](README-ko.md), [Português](README-pt.md), [Русский](README-ru.md), [Slovenščina](README-sl.md), [Українська](README-uk.md), [中文](README-zh.md)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -209,12 +209,19 @@ Notes:
|
|||||||
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
- To rename many files at once according to a pattern, use `rename`. For complex renames, [`repren`](https://github.com/jlevy/repren) may help.
|
- To rename multiple files and/or search and replace within files, try [`repren`](https://github.com/jlevy/repren). (In some cases the `rename` command also allows multiple renames, but be careful as its functionality is not the same on all Linux distributions.)
|
||||||
```sh
|
```sh
|
||||||
# Recover backup files foo.bak -> foo:
|
|
||||||
rename 's/\.bak$//' *.bak
|
|
||||||
# Full rename of filenames, directories, and contents foo -> bar:
|
# Full rename of filenames, directories, and contents foo -> bar:
|
||||||
repren --full --preserve-case --from foo --to bar .
|
repren --full --preserve-case --from foo --to bar .
|
||||||
|
# Recover backup files whatever.bak -> whatever:
|
||||||
|
repren --renames --from '(.*)\.bak' --to '\1' *.bak
|
||||||
|
# Same as above, using rename, if available:
|
||||||
|
rename 's/\.bak$//' *.bak
|
||||||
|
```
|
||||||
|
|
||||||
|
- As the man page says, `rsync` really is a fast and extraordinarily versatile file copying tool. It's known for synchronizing between machines but is equally useful locally. It also is among the [fastest ways](https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html) to delete large numbers of files:
|
||||||
|
```sh
|
||||||
|
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
|
||||||
```
|
```
|
||||||
|
|
||||||
- Use `shuf` to shuffle or select random lines from a file.
|
- Use `shuf` to shuffle or select random lines from a file.
|
||||||
@ -238,14 +245,14 @@ Notes:
|
|||||||
|
|
||||||
- To split files into pieces, see `split` (to split by size) and `csplit` (to split by a pattern).
|
- To split files into pieces, see `split` (to split by size) and `csplit` (to split by a pattern).
|
||||||
|
|
||||||
- To manipulate date and time expressions, use `dateadd`, `datediff`, `strptime` etc. from [`dateutils`](http://www.fresse.org/dateutils).
|
- To manipulate date and time expressions, use `dateadd`, `datediff`, `strptime` etc. from [`dateutils`](http://www.fresse.org/dateutils/).
|
||||||
|
|
||||||
- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files.
|
- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files.
|
||||||
|
|
||||||
|
|
||||||
## System debugging
|
## System debugging
|
||||||
|
|
||||||
- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jakubroztocil/httpie).
|
- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jkbrzt/httpie).
|
||||||
|
|
||||||
- To know current cpu/disk status, the classic tools are `top` (or the better `htop`), `iostat`, and `iotop`. Use `iostat -mxz 15` for basic CPU and detailed per-partition disk stats and performance insight.
|
- To know current cpu/disk status, the classic tools are `top` (or the better `htop`), `iostat`, and `iotop`. Use `iostat -mxz 15` for basic CPU and detailed per-partition disk stats and performance insight.
|
||||||
|
|
||||||
@ -277,7 +284,7 @@ Notes:
|
|||||||
|
|
||||||
- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc.
|
- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc.
|
||||||
|
|
||||||
- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig).
|
- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](https://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig).
|
||||||
|
|
||||||
- Check what OS you're on with `uname` or `uname -a` (general Unix/kernel info) or `lsb_release -a` (Linux distro info).
|
- Check what OS you're on with `uname` or `uname -a` (general Unix/kernel info) or `lsb_release -a` (Linux distro info).
|
||||||
|
|
||||||
@ -383,6 +390,8 @@ A few examples of piecing together commands:
|
|||||||
|
|
||||||
- `time`: execute and time a command
|
- `time`: execute and time a command
|
||||||
|
|
||||||
|
- `timeout`: execute a command for specified amount of time and stop the process when the specified amount of time completes.
|
||||||
|
|
||||||
- `lockfile`: create semaphore file that can only be removed by `rm -f`
|
- `lockfile`: create semaphore file that can only be removed by `rm -f`
|
||||||
|
|
||||||
- `logrotate`: rotate, compress and mail logs.
|
- `logrotate`: rotate, compress and mail logs.
|
||||||
@ -494,10 +503,13 @@ These are items relevant *only* on MacOS.
|
|||||||
|
|
||||||
- Be aware MacOS is based on BSD Unix, and many commands (for example `ps`, `ls`, `tail`, `awk`, `sed`) have many subtle variations from Linux, which is largely influenced by System V-style Unix and GNU tools. You can often tell the difference by noting a man page has the heading "BSD General Commands Manual." In some cases GNU versions can be installed, too (such as `gawk` and `gsed` for GNU awk and sed). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python or `perl`) or test carefully.
|
- Be aware MacOS is based on BSD Unix, and many commands (for example `ps`, `ls`, `tail`, `awk`, `sed`) have many subtle variations from Linux, which is largely influenced by System V-style Unix and GNU tools. You can often tell the difference by noting a man page has the heading "BSD General Commands Manual." In some cases GNU versions can be installed, too (such as `gawk` and `gsed` for GNU awk and sed). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python or `perl`) or test carefully.
|
||||||
|
|
||||||
|
- To get MacOS release information, use `sw_vers`.
|
||||||
|
|
||||||
|
|
||||||
## More resources
|
## More resources
|
||||||
|
|
||||||
- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources.
|
- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources.
|
||||||
|
- [awesome-osx-command-line](https://github.com/herrbischoff/awesome-osx-command-line): A more in-depth guide for the Mac OS command line
|
||||||
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts.
|
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts.
|
||||||
- [shellcheck](https://github.com/koalaman/shellcheck): A shell script static analysis tool. Essentially, lint for bash/sh/zsh.
|
- [shellcheck](https://github.com/koalaman/shellcheck): A shell script static analysis tool. Essentially, lint for bash/sh/zsh.
|
||||||
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): The sadly complex minutiae on how to handle filenames correctly in shell scripts.
|
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): The sadly complex minutiae on how to handle filenames correctly in shell scripts.
|
||||||
|
@ -36,3 +36,5 @@ roles:
|
|||||||
xuchunyang: translator (zh)
|
xuchunyang: translator (zh)
|
||||||
stevenlordiam: translator (zh)
|
stevenlordiam: translator (zh)
|
||||||
Armour: translator (zh)
|
Armour: translator (zh)
|
||||||
|
stepan0904: translator and maintainer (uk)
|
||||||
|
francescomalatesta: translator and maintainer (it)
|
||||||
|
Reference in New Issue
Block a user