Unix Tricks
cfenollosa.com
cfenollosa.com
In bash, "ESC" then "." fetches the last parameter of the previous command. It's invaluable (same as typing "!$" but you get to see and edit it)
More details in this Stackoverflow answer: http://stackoverflow.com/a/4010170/578588
It also has the side effect of "resurrecting" dead keys (which are unrelated to Option), making input of 'ê'and 'ï' impossible.
An alternative is using iTerm2 which has a similar setting, liberally applyable to either Option key.
shopt -s histverify histreeditEditing password is hackernews if anyone wants to tune up the markdown.
alias hist='history | grep'
Use it like this: $ hist git
9543 git add toto
9544 git commit
9545 git log
9546 git log
9548 git add -A
9549 git commit
9550 git log
9633 git pull
9955 cd dev/git
9957 git grep copyof
9958 git grep copyof
9959 git pull
By the way, do you know you can call back the 9633rd command in the history with "!9633"? !!
will be substituted with the last command you typed. So if your somebody like me who frequently types $ apt-get update
Could not lock yada yada are you root?
$ sudo apt-get update
instead you can type $ apt-get update
$ sudo !!Same thing for the last argument, it's easily edited if you know the right shortcuts: Ctrl-P Alt-B Ctrl-U. (Works for bash, for zsh you need http://stackoverflow.com/q/3483604/414272). That said, I didn't know about Alt-.
>Religious texts don't change over time due to community suggested changes.
Then I caught myself.
man hier
is pretty cool. It explains the root directory structure of the system.[1]: https://plus.google.com/+LennartPoetteringTheOneAndOnly/post...
"apropos Regular Expressions" brings up wild stuff: re_format(7) -- posix regex docs at last!, treereg(1) (huh????).
Some serious lore in here ...
Back in the late 90s when I first moved to Debian from Windows, growing up with a DOS CLI made the transition far easier to me (and having some FTP exposure didn't hurt either).
Yikes, I recently had to do a bit of development on a windows box and I found the command-line tools (not to mention CMD itself, which seems to have stopped development in 1993) to be absolutely awful. I could barely survive without Cygwin, git bash, etc giving me some semblance of a functional shell setup. I guess it's different strokes for different folks.
But the filesystem layout and set of built-in commands is pretty easy to understand fully. It's generally pretty easy to find things. In that sense Unix is more complex (but also more sensible, usually).
On the face of it, the basic directories are straightforward (Programs -> \Progra~1, User files -> \Docume~1, System files -> \Window~1, Very System files -> \Window~1\System32), but I don't recall having an easy time finding things (speaking from memories of my XP days).
Where would you look for a config file of some application? Maybe it'll be in \Progra~1. Or $user\LocalSettings. Or ApplicationData. Maybe in the Registry? (Don't get me started about the registry!)
Where would you look for log files? Does the Event Viewer show everything nowadays, or do you still have to hunt for logfiles in the same fashion as config files?
On *nix, I know that my configs are under /etc/ (global) and ~/.{program name}/ (user-specific), and my logs are under /var/log/. I don't know what every single directory is, but I know where to look for things when I need to.
Don't get me wrong, I still prefer living with bash and a full GNU system -- it's just sad about what MS did (or didn't) do with their command line tools since 2003ish and on.
http://blogs.msdn.com/b/powershell/archive/2007/03/19/monad-...
cmd.exe? Powershell?
Why do some distributions use /opt a lot while others don't seem to use it at all?
https://en.wikipedia.org/wiki/Unix_filesystem
"Contains locally installed software. Originated in System V, which has a package manager that installs software to this directory (one subdirectory per package)."
Solaris made extensive use of /opt, that flowed into some Linux packagers. It then fell out of favor as everyone put everything in /usr
You know what else I hate? Typing in long commands in the Mac OS X terminal and then them wrapping weirdly. Especially when I hit the up arrow to go back in my terminal history.
shopt -s histappend
export HISTSIZE=100000
export HISTFILESIZE=100000
export HISTCONTROL=ignoredups:erasedups
export PROMPT_COMMAND="history -a;history -c;history -r;$PROMPT_COMMAND"
I wish I could give credit to where I originally found this but it was ages ago.It looks like it clears your shell's history, and then re-populates it from the .bash_history file?
history -a # append history lines from this session to the history file.
#History file may contain history from other terminals not in this one so:
history -c # clear [in-memory] history list deleting all of the entries.
history -r # read the history file and append the contents to the history list instead.
I've heard that -n can be problematic which is why -c then -r is used. > You know what else I hate? Typing in long commands in the Mac OS X terminal and then them wrapping weirdly.
Yeah, keeping ctrl pressed in and pressing x followed by e (CTRL + x e) will open up the current line in $EDITOR and when you edit and save, replaces the current line with what you entered in your editor. Really a killer feature.Do this at the command prompt, or once in your ~/.bash_profile to make it permanent:
set -o vi
After that, you can search for any of the commands in your history, edit it, and then execute the edited command, by doing this:
At the prompt, type Esc once to get into vi command mode. Then you can press the k key repeatedly to scroll up through the command history, or (often easier) use the ? (search backward) vi command to search for a pattern to find a specific command. Once found, press v to edit it in a temp file. Then when you save and quit, the edited command gets executed.
The same technique works with emacs as the editor instead of vi, if you don't give the 'set -o vi' command, because the default editor for command line history is emacs. Also, if you have run 'set -o vi', you can switch the editor for commands back to emacs with 'set -o emacs'.
The 'set -o <editor>' bit sets the readline editing environment to be similar to vi. It can be set to emacs.
C-xC-e (edit-and-execute-command) invokes the editor specified by $VISUAL, $EDITOR, or emacs, in that order. You could set it to scrivner if you wanted to (though I'm not sure that would necessarily work on exit).
I've tested with VISUAL set to nedit, from which I then changed it to uptime. Now I get loadavg when I want to edit my command line ;-)
set editing-mode vi
in your ~/.inputrc (instead) and all GNU libreadline using programs will give you vi keys instead of emacs :-)
It's better than nothing though.
At the shell, it's true that you're limited to vi-style controls (so no text objects like ci").
However, once you press 'v' in normal mode you can drop into either vi or vim - this only depends on what $EDITOR is set to[1].
zsh has `setopt inc_append_history` and `setopt share_history`. i am sure bash has something similar.
Are you escaping your color codes in PS1 correctly?
Bad:
PS1="\033[1;32m \w \033[m $"
Good (notice the extra \[ and \]): PS1="\[\033[1;32m\] \w \[\033[m\] $"edit: couldn't get UTF-8 branch symbol to be properly displayed here, but this is how it looks:
http://i.imgur.com/zuq24gV.png?1
function fancyPrompt {
local bgBlue="\[\033[48;5;31m\]"
local fgBlue="\[\033[38;5;31m\]"
local fgWhite="\[\033[38;5;231m\]"
local bgDarkBlue="\[\033[48;5;24m\]"
local fgDarkBlue="\[\033[38;5;24m\]"
local bgDarkGray="\[\033[48;5;237m\]"
local bgLightGray="\[\033[48;5;245m\]"
local fgLightGray="\[\033[38;5;245m\]"
local colorClear="\[\033[0m"
local branch
local branch_symbol="\[\] "
if branch=$( { git symbolic-ref --quiet HEAD || git rev-parse --short HEAD; } 2>/dev/null ); then
branch=${branch##*/}
export PS1="${bgBlue}${fgWhite}\h${colorClear}${fgBlue}${bgDarkBlue}\[\] ${fgWhite}\w${bgLightGray}${fgDarkBlue}\[\] ${fgWhite}${branch_symbol}${branch}${fgLightGray}${bgDarkGray}\[\] ${colorClear}"
else
export PS1="${bgBlue}${fgWhite}\h${colorClear}${fgBlue}${bgDarkBlue}\[\] ${fgWhite}\w${bgDarkGray}${fgDarkBlue}\[\] ${colorClear}"
fi
}I've been loving a prompt which color codes git branches (which, if I understand right, would be built-in if I used zsh instead of bash) [0], though I have to edit the last line in order to get my history appendation working as well.
I solved this by adding the following line in my ~/.bashrc
shopt -s checkwinsize
Never tried on Mac OS X though, so I don't know if it works.For all people who dont use Mac OS X:
This happens because your PS1 is wrongly set and bash cant calculate correctly the length left of your line. Try it out, by going back to default with no colors and crap and see how long it goes.
For mac os x users. The above wont help, dont even try it.
So far over 130000 command lines (with timestamp & cwd) for past 2.5 years, just on my laptop.
I used to feel this way. Then one day I figured out how to enable this in Bash. Resulted in a confusing mess. Turns out you most likely want terminal sessions to be distinct until you end them.
Ctrl-x Ctrl-e nice tip!
I'm in general a big fan of the OpenBSD userland: straightforward and very, very well-documented. Real manpages, no religious "The full documentation for xyz is maintained as a TeXinfo manual" crap.
A well-conceived featureset and good docs are key to properly learning a platform. OpenBSD taught me a lot about Unix. If you later realize that Bash has some feature that you actually need, you can still install it.
Also anything that will run script wise on bourne will run as is under korn.
Though you may well find that it is historical, which one a user picks shell wise. People who started or worked a lot with Sun systems will be csh fans. Old vets more inclided to bourne, though very few. As for korn shell, that would be mostly down to AIX systems as that is the default upon them as with the other systems mentions, default wise. Then for Linux you will find a bias towards bash.
Least that is what I have observed.
Though history does give us some intersting trends and the awk, perl, python transition and preference will also mostly be down to when somebody got into unix as a whole. Again old school, awk. Old, perl and not so long ago the python brigade.
But that is just a rule in thumb and more helpful in explaining why there is a solo perl script when everything else done in xyzzy type encounters.
As for OpenBSD, good choice, I prefer it due to the file system layout and more akin to old school unix unlike Linux which is `creative` more than not in choices, so feels less at home.
Still back in the early days we had AT&T and Berkly BSD flavours and with that the ps command, oh the fun and games.
But least thinks a little bit more common across flavours than before and yet still each has there own quirks.
Shell scripts really don't scale development-wise over time.
Definitely agree with the rest of the points though.
sort -u
alias ..="cd .."
alias ...="cd ../.."
# etc
and of course `cd -` to jump to previous directoryNo! In emacs ctrl-r searches your command history. It happens that bash use emacs mode by default. All other emacs basic commands work too: ctrl-p, ctrl-n, ctrl-f etc...
If you are a vim user, and especially if you love venting how much you hate emacs, then please add this to your bashrc:
set -o vi
and now you can use vim command instead of emacs.
'meta-r' is bound to comint-history-isearch-backward-regexp
ssh -R 12345:localhost:22 server.com "sleep 1000; exit"
use ssh -R 12345:localhost:22 -n server.com
The -n flag tells ssh to only make a connection, without ever running a shell. This means it even works when you don't have shell access (say, with a command= entry in .authorized_keys).Also, I cannot recommend envoy enough in lieu of ssh-agent, if you're not using a GUI ssh agent already (e.g OSX keychain or GNOME keyring)
Last, I guarantee you don't want "$@" in those aliases, but either "$*" or $@ (certainly the latter).
-N Do not execute a remote command. This is useful for just for‐
warding ports (protocol version 2 only).
-n Redirects stdin from /dev/null (actually, prevents reading from
stdin). This must be used when ssh is run in the background.
[1]: http://www.openbsd.org/cgi-bin/man.cgi?query=ssh&sektion=1Ctrl-V: type next input literally (e.g. Ctrl-V [Tab] if you don't want [Tab] to autocomplete).
Alt-#: Prefix current line with "#" (don't execute it) and put it into history for later use.
I'm sometimes surprised how many people don't know these: Ctrl-U/K: kill line before/after cursor.
alias clip='xsel -i --clipboard'
Get tree view of directories
alias lst='tree -L 2 $1'
Also I use za to go up in directory tree
bash https://gist.github.com/chanux/1119556 fish https://gist.github.com/chanux/9411092
Or you could just use tmux which afaict is superior to screen in almost every way. http://tmux.sourceforge.net/
"\e[A":history-search-backward
"\e[B":history-search-forward
Type a few characters and hitting the arrow keys will show only commands that match those first few characters.It's so ingrained I had to actually do it in a shell to know what it was I did.
I can't replicate it now on my test box; it works exactly the way you say it should. It may be a terminal issue; I'm currently on Windows using cygwin to ssh to Linux.
This might be a zsh thing though.
Also, other emacs keys work like back: ctrl-b, meta-b, forward: ctrl-f, meta-f, start of line: ctrl-a, end of line: ctrl-e etc.
https://github.com/ziyaddin/jean
It would be nice to get all of these .bash_profile enhancements in as packages.
I suppose it could be improved to prompt for a brew/apt install if needed.
E.g echo "This would be contents of file" | someCommand /dev/fd/0
$ ls -l /dev/fd /dev/std* | column -t
lrwxrwxrwx 1 root root 13 Jun 27 16:32 /dev/fd -> /proc/self/fd
lrwxrwxrwx 1 root root 15 Jun 27 16:32 /dev/stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Jun 27 16:32 /dev/stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root 15 Jun 27 16:32 /dev/stdout -> /proc/self/fd/1
You can even access the file descriptors of other processes with /proc/${pid}/fd/; which is handy for (say) un-deleting a file that a process still has open.Another handy one is "process substitution" which lets you do the same thing with multiple streams by creating new file descriptors, and automatically turning them into /dev/fd/* paths:
someCommand <(echo "contents of file 1") <(echo "contents of file 2")
which is somewhat explained by: $ echo someCommand <(echo "contents of file 1") <(echo "contents of file 2")
someCommand /dev/fd/63 /dev/fd/62/proc/${pid}/fd/ is very useful for forensic purposes when you find some malware running that deleted itself and/or config files but still has a handle open to them.
!<cmd>
e.g. sometimes I forget the "ln -s" order of arguments (to which it gives me an error), so I follow it up with: ln -s !ln:3 !ln:2 TOOLS
...
* 'tree' instead of 'ls -R'
... apt-file search /bin/treeAlso this bash function from Mathias Bynen's famous dotfiles is a fantastic shortcut for colorised (and more) output from tree. https://github.com/mathiasbynens/dotfiles/blob/master/.funct...
Use dcfldd instead of dd if you want to see how far your dd operation is progressing...
dcfldd if=[infile] of=[outfile] sizeprobe=if
So. Much. Better.
dcfldd also has many other useful options - read the man pages - and note that you'll have to install it from your linux distro's package repo beforehand.
Sending a USR1 signal to a running 'dd' process makes it print I/O statistics to standard error and then resume copying.
$ dd if=/dev/zero of=/dev/null& pid=$!
$ kill -USR1 $pid; sleep 1; kill $pid
18335302+0 records in 18335302+0 records out 9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/sLinux doesn't. I don't know why; but Google in the past has told me that patches to add it were rejected about 10 years ago.
But I prefer not to have to manually keep sending that ;)
Not sure why he feels SMB is better, because in my experience, NFS usually works more smoothly and is easier to setup than SMB. But then, I don't usually use windows.
If your font is all messed up, echo C-v C-o. C-v puts you into a literal mode, and C-o gets you back into the normal character set. (You probably got there by emitting a C-p at some point.)
ProxyCommand ssh -T host1 'nc %h %p'
one should use this instead: ProxyCommand ssh -W %h:%p host1for cmd in $(compgen -c); do if [[ $cmd =~ ^[0-9a-zA-Z]+$ ]]; then eval "alias $cmd?='man $cmd'"; fi; done
in my .bashrc to alias command?=man command, saves some typing to get to man pages ( which I do very often )
# Put this script in a directory in your PATH.
# m: pipe man output through col and save to file(s).
mkdir -p ~/man # Only creates the dir first time, including all dirs in the path.
for name: # in $* is implied
man $name | col -bx > ~/man/$name.m
doneDo a "chmod u+x m" to be able to run it.
Then run it like this:
m ioctl stdio signal # or any other commands
Then:
pushd ~/man; view ioctl.m stdio.m signal.m; popd
to read those pages, now stripped of formatting characters.
% compgen -b # built-ins
% compgen -k # keywords
% compgen -A function # functions
% compgen -abckA function # everything
[1] http://www.cyberciti.biz/open-source/command-line-hacks/comp... for cmd in $(compgen -c); do if [[ $cmd =~ ^[0-9a-zA-Z]+$ ]]; then eval "alias $cmd\?='man $cmd'" ; fi; done
# had to escape the ? in the alias nameCool trick :)
$ brew info rust
$ r fo=stalVery handy if you do something silly like cat a binary file without piping it into strings -a
This restores the terminal settings and sanity restored. Note you will often find yourself typing without seeing anything, least until you enter and execute the sane.
Also asvise the following usage ctrl+c a couple of times to clear anything out of the input buffer queued up. stty -sane all good from here onwards and good time to play with od and remember the strings -a pipe next time.
while sleep 0.1; do nc -w 1 -z host 22; done
Useful when waiting for systems to boot. @reboot /bin/date | /usr/bin/mail -s "$(/bin/hostname) booted" root@example.com
If you don't want to configure postfix as a smarthost (which is not that hard and recommended if only to have mail queued for retry), use ssmtp. $ until-success ssh ...
If you have my sysadmin-utils installed:meh, I don't like htop. "atop" on the other hand!!!
`xterm -display :1 -e <command>`
This is useful when running automated tests on top of vnc.
python3 -m http.server 8080