Live data from Hacker News

Mastering Bash and Terminal

blockloop.io

141–150 of 186 posts

Re: Mastering Bash and Terminal

#141
Great post & thread, a tl;dr:

  Ctrl-r      search history
              - then Ctrl-r again to show next match
              - then Tab to show all options
  Ctrl-p      previous command or arrow up
  Ctrl-n      next command or arrow down
  export HISTCONTROL=ignoreboth:erasedups
              Add to .bashrc to avoid duplicate entries

  Ctrl-a      to beginning of line
  Ctrl-e      to end of line
  Alt-b       one word back
  Alt-f       one word forward
  Ctrl-k      delete to end of line
  Ctrl-u      delete to beginning of line
  Alt-d       delete to end of word
  Ctrl-w      delete to beginning of word
  Alt-Backspc same

  cd -        change to last dir
  pushd  mark current dir and go to 
  popd        go to marked dir 
  z           fuzzy cd, install from https://github.com/rupa/z
  j           fuzzy cd and more, install via autojump

  Ctrl-z      to background & suspend
  bg          recent background app continue running
  fg          bring recent background app to front
  disown -h   remove recent background app from current tty
  fg %n       bring nth app to front, e.g.: fg %2 for second

  less        better than cat, doesn't flood screen, same keys
  find        find files, e.g. find / -name 

  ag          install via the_silver_searcher, faster grep

  tree        shows dir like a GUI app, install
  !!          last command, e.g. sudo !!
  fish        bash alternative with more sensible defaults

  man bash    read more about bash

Re: Mastering Bash and Terminal

#142
post #89
post #71

Earlier quoted context omitted.

Consider for a moment that it might be better written and explained than man bash.

Which is quite sad, if you think about it.

If one thinks about it, one realizes that there's a difference between tutorials/guides and reference doco, and the world is happy to have both.

Re: Mastering Bash and Terminal

#143

Great post & thread, a tl;dr: Ctrl-r search history - then Ctrl-r again to show next match - then Tab to show all options Ctrl-p previous command or arrow up Ctrl-n next command or arrow down export HISTCONTROL=ignoreboth:erasedups Add to .bashrc to avoid duplicate entries Ctrl-a to beginning of line Ctrl-e to end of line Alt-b one word back Alt-f one word forward Ctrl-k delete to end of line Ctrl-u delete to beginni…

Here are some notes I took about ZSH that may be helpful to someone

* zsh bang

previous commands:

   !!  Previous command
   !-1 Previous command
   !-2 Second previous command
Getting individual arguments:

   !$   Last arg
   !*   All args
   !$:h Last argument, strip one level
   !!:1 First arg
Modifying commandlines

   !ls:$:h             Head
   !ls:$:t             Tail
   !ls:$:r             Rm Suffix
   !ls:$:s/user/dude/  Substitute user by dude
* Filename Modifiers

  :h	head (dirname)
  :t	tail (basename)
  :e	extension
  :r	remove extension

  :l	lowercase conversion
  :u	uppercase conversion

  :p	print command but do not execute
  :q	quote substituted words

* zsh globbing

  **/* 	Picks out all files and directories, recursively.
  ***/*	Ditto, following symlinks
  *	Any string, including the null string.
  ?	Any character.
  [...]	Any of the enclosed characters. Ranges of characters can be specified by
  separating two characters by a -.
  [^...]	Inverse
  [!...]	Inverse
  	Any number in the range x to y, inclusive. Either can be omitted.
  ^x	Anything except the pattern x.
  x|y	Either x or y.

  x#	Zero or more occurrences of the pattern x.
  x##	One or more occurrences of the pattern x.
globbing qualifiers

* file type

    (.) 	Regular files
    (/)     Directories
    (@)     Symlinks
    (=)	Sockets
    (p)	Named pipes
    (%)	Device
    (%b)	Block devices
    (%c)	Character devices
* permissions

    (r)     Readable by owner
    (w)     Writable by owner
    (x)     Executables by owner
    (R)     Readable by world
    (W)     Writable by world
    (X)     Executable by world
    (A)	Readable by group
    (I)	Writable by group
    (E)	Executable bu group
alternatively a chmod style syntax is supported:

    ls **/*(.:g-w:)
* Ownership

    (U)		Your own user
    (G)		Your own group
    (u:userid:)	User with userid
    (g:userid:)	group with groupid
example: list files belonging to user www-data with ls -l /(u:www-data:)

Modification and access time

    (m)	Modification time
    (a)	Access time

    (-)	Before
    (+)	After

    (M)	Months
    (w)	Weeks
    (h)	Hours
    (m)	Minutes
    (s)	Seconds
example: list files accessed last month with ls /(.aM-1)

file size

    (L)	File size (defaults to bytes)
    (k)	use kilobytes
    (m)	use megabytes
    (p)	use 512-byte blocks
example: list all files larger than 10 megabytes with ls /(.Lm+10)

dos2unix /~.(gif|png|jpg)(.) # ~ excludes

dos2unix (#i)/~.(gif|png|jpg)(.) # case-insensitive

ls =bob # Lists file anywhere in $PATH

ls /some_file # Lists file under current directory zargs -- /(.) -- ls -l # Ditto

* zsh Iteration

  for i (/home/**/q*) rm $i
  for i in /**/b*(u:miklophone:); do rm $i ; done
  for f in http://zsh.sunsite.dk/Guide/zshguide{,{01..08}}.html; do...
  zargs -- /**/b*(u:miklophone:) -- rm

* Renaming files with Zsh

Numerical prefix:

   $  i=1; for j in *; do mv $j $i.$j; ((i++)); done

   $  i=1; for f in *; do mv $f $(echo $i| awk '{ printf("%03d", $0)}').$f;
   ((i++)); done

   $  integer i=0; for f in *; do mv $f $[i+=1].$f; done
Rename all files from name.mp3 to Name.mp3:

   $  zmv `([a-z])(*).mp3` `${(C)1}$2.mp3`
Capitalize file

   $  zmv '([a-z])(*).pdf' '${(C)1}$2.pdf'
Replaces spaces with underlines

   $  zmv '* *' '$f:gs/ /_'
FOO to foo

   $  for i in *(.); mv $i ${i:l}
Rename pic1.jpg to pic0001.jpg ...

   $  zmv 'pic(*).jpg' 'pic${(1:4::0:)1}.jpg'
   $  zmv '(**/)pic(*).jpg' '$1/pic1:4::0:)2}.jpg'  # recursive
Remove spaces from filenames

   $  for a in ./**/*\ *(Dod); do mv $a ${a:h}/${a:t:gs/ /_}; done
Substitute r for l

   s/l/r[/]

   Unless preceded immediately by a g, with no colon between, the
   substitution is done only for the first string that matches l. For
   arrays and filename expansion, this applies to each word of the
   expanded text.

   The left-hand side of substitutions are not regular expressions,
   but character strings.

   Any character can be used as the delimiter in place of '/'. A
   backslash quotes the delimiter character.

   The character '&', in the right-hand-side r, is replaced by the
   text from the left-hand-side l. The '&' can be quoted with a
   backslash.

* zsh if # see also -z below

  if [[ $foo = '' ]]; then
  print The parameter foo is empty
  fi
# quote the term to avoid pattern matching (not regexp, btw)

  if [[ biriyana = b* ]]; then
  print Word begins with a b
  fi
# Numbers

  if [[ $number -gt 3 ]]; then
  if [[ $number -lt 3 ]]; then
  if (( $number > 3 )); then
  if (( 3 )); then
# Files

  if [[ file1 -nt file2 ]]; then		# newer than
  if [[ file1 -ot file2 ]]; then		# older than
  if [[ file1 -ef file2 ]]; then		# same file
# Variables

  if [[ -z "$var is blah; test fails" ]]; then		# zero length?
  if [[ -n "$var is blah; test passes" ]]; then		# non-zero length?

Re: Mastering Bash and Terminal

#144
post #20

Earlier quoted context omitted.

zsh was quite popular when I first went spelunking in *NIX-land (2005). oh-my-zsh, which was a decent boost to zsh popularity, seems to have been around since 2009 ( http://ohmyz.sh/ ). zsh has always been held back by the "default browser"-syndrome: Linux and Mac OS both come with "good enough" default shells, so few people actually want to go through the effort of switching. Especially since there is a bit of a lea…

The problem with installing zch on my desktop is that I won't have it on the servers I SSH into. I need to know the proper spells and incantations that will work on a wide variety of distros and versions, many of which I don't personally maintain. Therefore, bash.

Conversely: I have the Z shell on all of the systems that I SSH into, ranging from OpenBSD to Debian Linux. I even have it on Interix on Windows as well. Many of them also have the Almquist shell and various flavours of the Korn shell available. A few even have the Thompson shell. (-:

Re: Mastering Bash and Terminal

#145
post #123

Earlier quoted context omitted.

My personal favourite trick with ":r!" is, in a new buffer, running :0r! grep -rn $pattern $path_to_directory or any other command that outputs lines containing "$path_to_file:$line_no" (eg most linters). With that output read into a buffer, placing the cursor anywhere in the "path:line" part and hitting ^wF will open that file in a new split window, and jump the cursor straight to the indicated line - or you can do…

With the likes of :cfile :cbuffer one can turn that file/buffer directly into a quickfix list, where simply enter will take one to the relevant position. Messages with column positions are recognized in quickfix lists (:help errorformat).

For any commands or pipelines, you can use:

    :cex system('git grep -n foo | grep bar') | copen
then :cn and :cp to step through the list easily.

Re: Mastering Bash and Terminal

#146
post #125

Those Emacs commands you mention for moving around on the line also work in a lot of other text fields, in a lot of other programs. Notably they don't work in MS Office, but they work in web browsers and practically every other app I have on my Mac.

They work in so many things because they're the default keybindings for the movement commands in readline. So anything using readline gets them for free.

Re: Mastering Bash and Terminal

#147
post #128

I've tried bash, zsh, and fish. After trying all three, I'm staying with fish. bash and zsh don't have sensible defaults, and configuring them is tedious. fish works great out of the box, and it's really fast. When I picked up zsh I used oh-my-zsh and later prezto, but it was slow and figuring out what everything all the framework did was complicated. With fish I have a setup.fish script that defines all my universal…

I use fish too but I'm thinking about switching back to zsh. Mostly due to incompatible software here and there (like nvm) and lack of completions for a lot of cli tools.

I leave my $SHELL set to bash, but have tmux launch fish. That way, any software that tries to start a shell of its own gets the POSIX sh-compatible shell it expects.

Re: Mastering Bash and Terminal

#148
post #112

Another trick is to use "!!" which is the last command launched, especially useful if you forgot a "sudo" in front of your command, just write sudo !! In the same way, "!*" is all the arguments of your previous command, and "!$" only the last one.

Came here to mention the sudo-bang-bang trick, which really has the best name of all the commands I know.

Re: Mastering Bash and Terminal

#149

Rather than temporarily suspend vim to use the terminal you can get vim to suspend and resume itself with the exclamation mark command. This has the benefit of not wreaking havoc on your vim session and allowing you to read data into vim by prefixing with r. For example :!ls will execute ls and show you the result (press enter to return) :r!ls will read the result of ls in for you More usefully :r!sed -n5,10p that/ot…

Interesting. Your use of `git commit -am` resounded with me. I can't stand doing `git add .` ; `git commit -m "message"`; `git push`. I aliased "commit" to "ci" in git-config, and then do `git ci -am "message" && git push`. I'm sure at some point I will add a hook to have the push done automatically (though sometimes I prefer to do it manually, so I will have to make a decision.) I am an avid emacs user though. I rea…

You can also look at https://github.com/scmbreeze/scm_breeze
Post reply on HN