(Useful) Stupid Unix Tricks?
So the other day I messaged another admin from the console using the regular old 'write' command (as I've been doing for over 10 years). To my surprise he didn't know how to respond back to me (he had to call me on the phone) and had never even known you could do that. That got me thinking that there's probably lots of things like that, and likely things I've never heard of. What sorts of things do you take for granted as a natural part of Unix that other people are surprised at?
rm -rf /
Well.
dd if=/dev/zero of=/dev/sda1
screen is awesome.
The World Wide Web is dying. Soon, we shall have only the Internet.
... Generally people are surprised by the fact that you could type some strange incantations into a black window like awk grep etc and make the computer do things without touching the mouse. Yeah, some are surprised by that thing.
sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
It doesn't crash?
"Do what you can, with what you have, where you are."
One command I really like is,
"du -s * | sort -n"
This lists the size and name of every file or folder in a directory and orders them from smallest to largest.
So much easier for me to use than perl. I presume the modern unix user prefers perl.
I find a combination of find/grep to be pretty useful. Not sure about how unknown it is, but I do know that several UI-based linux admins around our office don't know about "stacking" commands. (I know, I know, one would think they would be mutually-exclusive
find . | grep [string]
Hi, I Boris. Hear fix bear, yes?
I once worked with an admin that wrote a program that wrote directly to a users terminal and prompted in the same way "write" did. One notable exception is that he let you put whatever username@hostname you wanted.
I got quite a few requests from "yourmom@pronindustry.com" to chat...
I'm sure everyone at some point is surprised of tabbed completion.
And I've been administering Linux systems for awhile now. Step back for a moment and you'll find that "man pages" and "info" are actually a pretty awful way to distribute documentation. As a supplement they'd be fine, but as the main source of information on how to use many commands... not so much.
I discovered if you give the echo shell command an asterisk as a parameter, it dumps out the file names of the current directory. (The sad thing is I had a practical use for this when a less-than-clueful-collegue deleted the /bin directory, leaving the system without an ls program).
--
Luck is just skill you didn't know you had.
Works like a charm for finding a file containing a keyword. Another one I often use is:
Human readable disk space:
Track down where your space is going:
Javascript + Nintendo DSi = DSiCade
A sys admin was recently surprised that I didn't use screen. My explaination was that all that C-x stuff reminded me too much of using Emacs.
Moderators are free to mod this Flamebait or Insightful, depending on personal bias.
Not a typewriter
I've seen Windows people go slack-jawed in astonishment as I ssh to the other side of the world and run X programs over forwarding.
Some refuse to believe it, others shake their heads and walk away.
On the older systems, talk was a great utility.
dd, device duplicator / disk destroyer
mount, what I can't have a desktop icon?
also managing disk volumes and the old conventions of /opt, /u, /usr, /usr/local
This new fangled Linux craze with all of the UI tools is feeding it. Redhat is training admins that are dependent on a given release of their enterprise software (which I am a huge fan of) but not teaching them how it works under the hood.
How about slirp? scp?
The one ray of hope seems to be a new generation hacking their bsd and linux based (iPhone/Android) phones and having fun in a somewhat embedded (but full blown) *nix environment.
Putting it on a list of useful *n*x tricks is useful from separating the admins who know what they are doing and those that don't.
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
I personally like all the little command shortcuts you can use in Bash, such as command searches using history modes (!?, Ctrl+r, etc.), command replacement using ^search^replace, last known argument using 'Alt+.'. That sort of stuff. There's tons of it out there, most of which I'm not too familiar with.
Search and replace inplace in files, using perl:
perl -pi -e "s/searchme/replaceme/g" *
In all .cpp anh .h files:
perl -pi -e "s/searchme/replaceme/g" `find . -name \*.cpp -o -name \*.h`
Or if you're a bash person:
perl -pi -e "s/searchme/replaceme/g" $(find . -name \*.cpp -o -name \*.h)
In terms of navigation directories efficiently, I find that "cd -" is often forgotten (changes directory to your previous directory). I personally find it very useful, and couldn't live without it!
Showers
Help! I'm a slashdot refugee.
Though I really have no idea why:
/* >> biglist
find
grep -i $SOMETHING biglist
Actually that hasn't impressed anyone in a while, come to think of it. At least not since Apple figured out what a find index is.
The rev command has got to be one of the most useless Unix commands I've ever come across. It's almost as if someone's first c program somehow got taken up as a part of standard Unix! Maybe in the days before sed and awk and perl it had some function in pipes that I can't grok, but nowadays other than making hints for video game websites I can't imagine what it's for.
Unhackable encryption of course.
$ configure . --ignoretroll
Configuration aborted. Installation files deleted. Uploader banned.
$
Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
Before IRC and IM there were finger and talk. They don't work as often as they used to because admins generally don't open them up to the public. But, you used to be able to see if someone was online using finger and then chat with them using talk.
finger user@example.com
talk user@example.com
You can usually still use these with another user on the same host as the author did with write.
fg, bg, kill, Ctrl-Z, &. Learn it. Know it. Live it.
Even if they do know about job control, I've seen people look for a background job with ps, and then kill it using the PID. In most shells you can just do kill %, e.g. kill %1
Hands in my pocket
Synaptic Package Manager is a GUI thing that comes with Ubuntu and has a search function. You just put a checkbox next to the packages you would like to install and press "apply".
meh
You're not giving echo an asterisk as a paratemer. You're giving the shell an asterisk, which it dutifully expands. echo (which in this case is a shell builtin, but it doesn't have to be then just echoes them back.
This isn't some echo peculiarity. It works for anything, even commands that don't normally take files, or even with files that look like switches (conversely, if you want to treat all subsequent arguments as files, not switches, most programs have a '--' switch):
$ ls
a -l b c
$ ls *
-rw-r--r-- 1 marcansoft users 0 2008-11-05 21:58 a
-rw-r--r-- 1 marcansoft users 0 2008-11-05 21:58 b
-rw-r--r-- 1 marcansoft users 0 2008-11-05 21:58 c
$ ls -- *
a -l b c
In the second example, ls sees "ls a -l b c" and takes -l as a switch instead of a filename.
This shows all attached block devices (it also errors like crazy, hence the | more)
/dev/* | more
blockdev --report
Useful sometimes! Also shows disk size and stuff.
:(){ :|:& };:
The World Wide Web is dying. Soon, we shall have only the Internet.
People used to use finger all the time to see what the sysadmins (myself included) were doing. Link your .plan to a massive core file, or several core files >> together ....
Quite a handy way to switch between several applications on a single terminal: Ctrl+Z stops the current program, then bg to resume it and send to background, fg to resume in foreground. You can have several stopped programs and pick one with fg 3, for example. See all stopped jobs with jobs.
Few things to note, wget still prints to STDOUT, even when backgrounded, so I run it in screen. Also, pico may require a -z switch to allow suspension.
Hell, I think it's probably a GNU extension, because it's still not in Solaris.
I think rgrep appeared around BSD 4.4, though.
Oh well. I still surprise people with backticks. *sigh*
Do daemons dream of electric sleep()?
One great feature of find that many people are unaware of is that you can use -exec as a test, not just as an action. For example, this is equivalent to your command above:
find . -exec grep -q {} \; -print
The "-print" action is only executed if the -exec command returns success.
You can do a lot of handy things with this. Here's a real-world example from earlier today. I wanted to change the mime-type of all the xml files in my svn repository from "application/xml" to "text/xml":
find . -name \*.xml -exec sh -c "svn propget svn:mime-type {} | grep -q application/xml" \; -exec svn propset svn:mime-type text/xml {} \;
chmod a+x /bin/laden
Done!
I sometimes use rev to sort text by the end of the line, not the first. This is often useful when comparing two similar file structures.
For example:
$ wc -l foo/* bar/*
6 foo/dead.letter
86 foo/xorg.conf
6 bar/dead.letter
54 bar/xorg.conf
$ wc -l foo/* bar/* | rev | sort | rev
86 foo/xorg.conf
54 bar/xorg.conf
152 total
6 foo/dead.letter
6 bar/dead.letter
(Yes, I'm aware you can use sort -k to specify the sort key, but this is quicker and easier)
Whenever I want to know _what_ I did, I'll fire up script and capture my keystrokes.
If your system has it, you can "watch" yourself with scriptreplay
God is good all the time! -K
This is an important difference between unix shells and dos/windows shell. In Unix, the wildcards like "*" are handled by the shell and expanded before the program ever sees the arguments. In DOS/Windows, the expansion must be done by the program itself. This is why every program in unix understand wildcards, while only some do in the MS world.
Assuming you already know the simple stuff like how to use shell quotes correctly, what you can do with ps and top, ...
Need to know the serial number of a server or bios version or many other things dmidecode is your friend.
When I pop up with my laptop to discuss with a colleague, after a while I might do on their computer:
xhost +mylaptopname
and on my laptop I do:
x2x thecomputername:0 -west
Then suddenly my mouse can go over the two computers, my keyboard works on both as well, and I can even copy-paste between the two computers. It looks like the two computers got united. In a flash, newbies get a new idea of what means unix and X ;-)
The advantage of the directory stack over "cd -" is that the directory stack always remembers where you last were. "cd -" only remembers until you change directories again.
In tcsh (I don't know other shells), you can do directory stack substitution. =0 is current directory, =1 is one up, =2 is two up, and so on.
I also use bindkeys to bind Control-G to 'dirs -v' so I can look at the directory stack with ease, even in the middle of a command.
Personally, I think directory stack commands are the least-known, but most useful feature in tcsh.
The ultimate goal of science is to unify all forces of nature to a single law that can be silk-screened onto a T-shirt.
!! in bash uses the last command you entered. $ make_me_a_sandwich What? No. $ sudo !! okay. $
To find a string in a file I used to do "find . | xargs grep foo"
It's generally wise to use -print0 and -0...
Finally! A year of moderation! Ready for 2019?
Actually, you don't need fingerd running if you looking at the local machine. IIRC it reads the local wtmp or wtmpx file to get the information.
ls -l | sort -n +4 -- sorts files in size order, good for finding big files in a directory
du -s * | sort -n -- similar to above, find the biggest files & subdirectories of the current dir
du | xdu -- only when you're in X, obviously. Better grain than above, with the ability to drill down into subdirectories
ls -d /dev/* | egrep -e '^/dev/[h|s]d[a-z]$' | xargs -l1 -r shred -vfz -n 100
Summary: Reorganizes* the data on your disks for maximum read performance.
* Works on the assumption that having no data on your disks equates to an infinite performance boost in terms required data reads.
Embedding output... use the backtick, not the doubletick. '`' not '"'
echo There are `ls | wc -l` entries in this directory.
In ksh, you can also use the syntax $(command string)
echo There are $(ls | wc -l) entries in this directory.
Mark J. Cecil -- Senior UNIX Engineer
New Orleans, Louisiana
http://notrealswift.blogspot.com
Well, to be fair it's a relatively new feature in bash, so perhaps ubuntu is just the first place you've tried that makes bash completion the default. Here's a blog posting on changing completion to make it smarter, so perhaps you can follow some links and learn how to make the shell do what you want. That's sort of the point...
Instead of using find and xargs it's sometimes easier to use the -exec parameter to find:
find . -type f -exec ls -l {} \;
xargs is very useful in other circumstances. One thing that I get asked about a lot is how to pass variables. Main thing to remember is to call the shell via xargs to process variables and other parameters.
BTW: How does one ork a cow?
BTW: How does one ork a cow?
Very, VERY, carefully.
Add this to your .inpurc file:
Then you can do it either way. <Ctl-Space> works like Windows, tab works like bash. Also add these if you want a little additional sanity:
ls -l 'locate gcc' // Output would give you a long listing of wherever gcc is located
Maybe it is just my font, but I think those should be backticks. Variables and commands cannot interpolate strings with single quotes ''.
Backticks, however, will allow command output redirection.
ls -l `locate gcc`
You could write it this way, but you threw in double-quotes and do not really need them here.
find ~/tvshows -name doctor\*who\* -exec mplayer -fs "{}" ";"
You could type the following, with the same effect. The find command with the -exec switch, is forking off a sub-shell for every argument passed by the find command, the \; or ";" is a command terminator for the sub-shell which is forked off. Depending on the task this could run very, very, very slow. For heavy-duty tasks there is a pretty neat utility shipped with every distribution of Perl, check out find2perl sometime.
find ~/tvshows -name "doctor*who*" -exec mplayer -fs {} \;
To generate pure Perl code to do the same loop, run the following. If you tack on a '| perl', after the find2perl command, it will pipe the generated code straight to the language interpreter and execute.
find2perl ~/tvshows -name "doctor*who*" -exec mplayer -fs {} \;
/^([Ss]ame [Bb]at (time, |channel.)){2}$/
My previous place of employment was a Mac shop, where I discovered the wonderful pbcopy and pbpaste commands. Why they aren't a standard part of every X windows distribution, I'll never know, but they are damned handy.
What they do is allow you to read and write from the cut-and-paste buffer from the command line. "pbpaste" will print the currently copied text to stdout, while "pbcopy" will replace the buffer with stdin.
Fortunately, there are some third-party X equivalents for this, such as xsel or xclip, which can be adapted to work in the same way.
Rougly equivalent:
pbcopy
xsel -i --clipboard
xclip -in -selection clipboard
pbpaste
xsel -o --clipboard
xclip -o -selection clipboard
echo '[q]sa[ln0=aln256%Pln256/snlbx]sb3135071790101768542287578439snlbxq'|dc
grep --color
For some reason, many people are greatly surprised when they figure out that grep will highlight matches for them.
The find command is definitely a good tool to be familiar with. Also, I've done a lot of really wacky stuff with sed in the past. (and sed experience can help you to work with ed and even ex, for those times the system has crashed so hard that's all you've got) (though I don't think I've had that happen since I left Ultrix).
dc and bc are good things at times. Really, I do a whole lot of really complicated manipulation of data with the various utilities, sometimes all in one long pipeline and sometimes in multiple complicated stages. An example of that is where I'll often take a du output, use sed to convert G, K, and M to the proper amount of zeroes (or maybe there's a du option to do that automatically, I forget), awk out the 1st column and print each as "$1 +" with no returns, echo a "0" at the end, and pipe the whole thing through bc, to get a "grand total." (maybe that's a bad example, but the ([do something]; echo 0) | bc is definitely something I've done a lot over the years.
I used to have aliases to call dc to do radix conversion (like echo "2 o 1337 p" | dc to get "10100111001"). (there's also a great .sig line out there that does some kind of crazy dc stack program to print out an ascii message, that I wasted a good chunk of time figuring out on paper to understand how it worked).
Another great trick I've been using for 20 years is dd piped through ssh, to copy a local hard drive image over the net to another machine, or vice-versa (well, okay, 20 years ago it was rsh). (like boot off a live CD, "(ssh remote cat /my/image.dd) | dd of=/my/dev" to rebuild a local drive from a remote backup.
There are lots of other things, way too many to write here. I'm sure there's a website out there somewhere.
Oh, and another great one from the days when I'd get files with untypable characters in the filename -- "ls -i" to get a files inode, then "find . -inum [inode] -exec rm {} \;" to delete that (or mv {} newname to rename it). Not sure I need that much any longer, but at the time it was VERY useful.
Maybe an ex-windows user who assumed "delete /bin" was the linux equivalent of "empty wastebasket" ?
lsof is a LIFE SAVER for trying to find what's still using something in a mounted resource when trying to unmount something. For example:
/mnt/myMount
/mnt/myMount open
/dev/snd
lsof
That will list which processes have anything under
It's also useful to find who's accessing what device. For example, say you're trying to listen to an mp3 and Amarok bitches about the sound device not being available. In that case, you could do something like this (assuming you're using ALSA):
lsof
That will list what processes are accessing any of your ALSA sound devices.
When I want to copy entire directory trees to a remote system while preserving all file attributes:
tar -czf - some_dir | ssh user@remote.host 'tar -C target_location -xzf -'
This also works when you want to copy something to a system that doesn't support scp (embedded devices)
Back in college where I met my first Unix systems we used finger to show if someone was online and then used talk (or was it ytalk?) to chat .. very useful for punctuating the intense concentration of some computer lab sessions.
Also, Yum is good for reducing stress by conveniently giving you ten minutes to an hour of relaxation time while it completes each operation.
Advanced users are users too!
There are a whole bunch of "history" tricks, to recall old commands without using the mouse.
When I started college, I studied the shell's man page until I knew them all. Some are so obscure I have forgotten them.
Generally, these involve an '!' character in some way.
Here are a few I use:
!! # run again the last command that was run
!9 # run again the command with history number 9
!v # run again the last command that started with a 'v'
!vi # run the last command that started with "vi"
!?foo? # run the last command that had the string "foo" anywhere in it
diff oldfile newfile
mv !$ !^ # same as "mv newfile oldfile"
# !$ is last arg of previous command, !^ is first arg
ls foo bar baz
rm -f !!* # same as "rm -f foo bar baz"
# !!* repeats all arguments from previous command
There are actually some baroque tricks that recall a previous command and perform a search-and-replace on it, but for anything that complicated I just recall the line and edit it. The baroque tricks would have been pretty darn cool back in the paper teletype days, though.
By the way, the Bash shell can be configured to edit command lines using vi or Emacs commands. I described how to do it in an article I wrote for Linux Journal magazine. It's the last section, "vi or Emacs Mode in the Shell".
http://www.linuxjournal.com/article/8361
Oh, not exactly a history trick, but here's something I use all the time: /tmp/files /tmp/files # edit list to include just the files I want /tmp/files`
ls -1 >
vi
rm `cat
# `cmd` inserts the standard output from cmd into the command line as if you typed it
ls -1 > /tmp/files /tmp/files :%s+.*+mv & /some/directory/path/&+ /tmp/files
vi
# edit list to include just the files I want
# now run this command:
# save file and quit vi
source
This moves the chosen files to "/some/directory/path". The breakdown of the vi command is as so:
: # invoke "ex mode" for search and replace command
% # run the following command on every line of the file
s # do a search and replace
+ # use a '+' for the command delimiter, so I won't have to backslash escape '/' chars in the path
.* # all characters on the line /some/directory/path/& # replace "foo" with "mv foo /some/directory/path/foo"
+ # end the match pattern, begin replace pattern
# & refers to the match pattern, thus all chars on the line
mv &
Takes less time to do it than to explain it!
The above is perhaps overkill if all the files are going to the same place. It's great if you want to send some files one place, some to another, because you can just edit the destinations until it looks right.
steveha
lf(1): it's like ls(1) but sorts filenames by extension, tersely
My system booted up fine, so of course the first thing I wanted to do was make it happen again.
Thirty seconds after the output finished and I'm looking at the garbled POST screen again. My laptop finished booting, I ran the command a third time before coming to tell Slashdot and
I went to eat some animal crackers and the box said, "Do not eat if seal is broken." I opened the box and sure enough..
GNU spoils us Linux folks. The 'date' command on any non-GNU system is like GNU date's retarded little brother
Check out my sysadmin blog!
(otherwise it will get killed the moment you log out)
I'd say most people don't know how to use SSH very well...
Stop typing passwords for every system: ssh-keygen, ssh-auth and ssh-add.
Transferring files both with scp/sftp and ssh user@host "cat file" > file, and the like.
Changing encryption algo for significantly improved speed, eg. -c arcfour
Enabling/disabling compression for internet/intranet. -C
An $HOME/.ssh/config file to map names to IP addresses, specify the default user names for each host, toggle compression per host, enable/disable port forwarding, keepalive, etc.:
host webserver
ForwardX11 no
ForwardAgent yes
Compression yes
hostname slashdot.org
port 2100
user cmdrtaco
And parenthesis and backticks seem to be going out of fashion in short order... Too bad, since they're quite time-saving: mkdir `date +%Y`
Slashdot gets worse every day... Pipedot: News for nerds, without the corporate slant
...at my uncle's dino-farm! He was so thrilled when I could help him. I was like, "I know this! It's a Unix operating system!"
The CB App. What's your 20?
For example, I did these to some of my favorite people:
banner "PORN HERE" > /dev/pts/4
echo "All files deleted." > /dev/pts/3
cat dictionary.list > /dev/pts2
--Chag
I can't live without svn. Svn is a revision control repository, usually used for source code. What makes it really powerful is that you can _easily_ have a history of everything that has changed in a file and when. On my systems, I keep /etc in svn, plus bind's zone files, plus all the non-image web content, and the "Network Documentation" folder.
Second trick, rsync. I use it to backup my home directory to another box. Very nice when you go through a hard drive/year.
Screen -x was my next pick, but somebody already mentioned it.
"echo ProtocolKeepAlives 120 >> /.ssh/config" No more dropped ssh sessions because of stupid nat boxes.
su -u Username -s .. become Username, but keep the current shell. Good for diagnosing permissions problems when the user has a /bin/false shell. (named/www-user/backup/etc).
A little awk goes a long way. Not the big-bad-I-am-a-programming-language-awk, but the smaller-friendlier extract one or two columns of text from something awk. ex. awk '{print $2}' prints the thing in the second column. Add -F the field separator tool and it gets really useful.
Better example. Here is a postfix log line.
Nov 5 16:27:19 pdc postfix/smtpd[13601]: 92B3F499C25F: client=exprod5mx254.postini.com[64.18.0.49]
Here is the awk to extract just the message id. awk -F': ' '{print $2}'
And here is the "I didn't get this message your mailserver must have eaten it" disprover. It searches the maillog for every message from or to a given address and extracts the full email transaction for that message id.
grep -i user@domain.com /var/log/maillog | grep smtpd | awk -F': ' '{print $2}' | sort -un > temp.fil && grep maillog -f temp.fil
Next trick, back ticks. `` Back ticks substitute the output of a command within a command.
Ex. Name a file after the date. echo "hi" > `date +%Y%M%d`.txt
On the subject of dates. date -d'yesterday' or 'last week' or '-4 hours' can be handy.
Last one. Loopback nat with Iptables, so you can access local hosts by their external ip. (Instead of setting up split dns.)
iptables -I POSTROUTING -s $local_network -d $local_network -j SNAT --to $lan_interface
My local network is 192.168.0.0/24 and the netfilter lan ip is 192.168.0.1, so that becomes...
iptables -t nat -A POSTROUTING -d 192.168.0.0/24 -s 192.168.0.0/24 -j SNAT --to 192.168.0.1
-ellie
That is exactly why you should never:
a) give friends accounts on a Linux box in your dorm room
b) keep your speakers turned on
c) keep the machine running while you sleep
I speak from experience
I actually run updatedb as nobody (who has no access to /home). There isn't much change under / anyway. For my home dir (which changes much more frequently) I do "find -type f > ~/ffind-db" every time I feel like the index might be out of date, and when I need to find anything I just do "ig $SOMETHING ff[tab]" (it autocompletes to "ffind-db", and "ig" is an alias for "grep -i"). Pretty handy.
Even better: use NX (http://www.nomachine.com/ - includes a "free edition"). Basically heavily compressed X forwarding, but also includes niceties such as being able to disconnect and reconnect sessions without killing the X clients. I use it over a VPN on the rare occasions I work from home, on a standard ADSL connection. Typing on an NX forwarded xterm is almost as quick as when SSH-ing in directly (which may seem a somewhat pointless use-case, but is the closest I know how to get to the behaviour of "standard" SSH with X forwarding). I also find I get *much* better responsiveness if I run VMWare Server Client on my work box, forwarded over NX, instead of running the client at home and connecting to the work VMWare server from there.*
Also available as FreeNX (http://freenx.berlios.de), but harder to set up IME.
* Which may just be another way of saying "VMWare's protocol sucks", but regardless, turns it from near unusable to very useful.
You want subtle?
ln -f /bin/rm /usr/bin/diff
"A goldfish was his muse, eternally amused"
If you begin your scripts with:
/bin, so this is VERY portable.) This also makes it easy to try out new interpreters (load a test version's binaries in ~/python-beta, add that first to that PATH, and now the test version's interpreter is used.) This does have the extra cost of starting up /bin/env first, but often that's not a big deal.
#!/bin/env python
and replace "python" with whatever your script interpreter is, then you can have the script automatically use whatever interpreter is first on your PATH. This is especially nice if you're "not sure where the interpreter executable is", e.g., it might not be in "/usr/bin" - so this helps portability. (The POSIX standards GUARANTEE that "env" is in
Yes, this is a bad idea if the attacker can control the PATH & this is security-relevant. But you can't securely run most interpreters directly anyway, so that's usually not relevant.
- David A. Wheeler (see my Secure Programming HOWTO)
cal 9 1752
We must repeat.
What the hell all those geeks are talking about?
who;uname;talk;date;wine;cd ~;talk;touch;talk;touch;more;finger;mount;fsck;yes;more;yes;yes;umount;make clean
One of the most timesaving things I ever did was to replace the default sh or bash with zsh.
zsh has so many features, it would be impossible to list them all here. In fact, I can't claim to know them all, but everybody takes what works for them.
Suffice to say that the completion, iteration, history and redirection tools are second to none if you're as lazy a typist as I am.
(posted with pbcopy)
503 sudo apt-get install xclip
504 echo xclip -in -selection clipboard > bin/pbcopy
505 chmod ug+x bin/pbcopy
506 echo xclip -o -selection clipboard > bin/pbpaste
507 chmod ug+x bin/pbpaste
508 history | pbcopy
"Be grateful for what you have. You may never know when you may lose it."
> There's two kinds of real UNIX Admins.
Actually, there are 10 kinds of UNIX admins...
From my .bashrc:
# Reminder: C-R to search history, alt-. to have last argument of last command
export HISTFILESIZE=1000000 # large total history limit
export HISTSIZE=1000000 # large bash instance history limit
export HISTCONTROL=ignoredups # ignore consecutive dups
shopt -s histappend # merge together history of different bash instances
PROMPT_COMMAND="history -a" # immediately save each command to history file
This is probably the most fun I've ever had. Since random is usually generated by different intervals 'from' the mouse, it'll keep on running and click on stuff all over the screen.: cat /dev/random > /dev/mouse
Also this makes some pretty interesting sounds. Last time I tried it didn't work, but it may with older kernels.:
cat /dev/kcore > /dev/dsp
I've made the best scripts at work. I aliased a script for ls that'll print out files in the directory spelled out in dots, and it makes a dot-matrix type sound for each one with the beep command. You've got other fun things like wtf, cowsay, cowthink. Or you can watch pr0n at school over SSH with aa-xine.
And don't forget the awesome cron job that plays at 1AM every morning for the night shift that blares out LEEEEROOOOOY JEEENKINS! My speakers are usually turned off when I come in the next day. I just want to make sure that no one is falling asleep on the job. :-p
PHB: Do we have Eunuchs here?.. I heard it is very important for a company's IT department to have Eunuchs.
Dilbert: I think you mean Unix. Yes we have a lot of Unix machines here.
PHB: Oh... [pauses and thinks]... If the company nurse comes by, tell her I said, "never mind."
-- I ignore anonymous replies to my comments and postings.
In complete seriousness, this was my first Linux experience. I got everything installed, read about this thing called safelib which was supposed to replace libc with safer wrappers, and tried to set it up. "su; rm /lib/libc.so.5; cp /tmp/path/libsafe.so /lib/libc.so.5". Rebooting clearly didn't fix it either :-)
A witty [sig] proves nothing. --Voltaire
Another alarm clock of sorts..
for i in `seq 1 10`; do echo wake up | festival --tts ; done;
Good for scaring the cat too.
Using tar to copy a directory tree can be fun, but for true amazement you need to combine it with a remote shell to copy an entire directory tree to a different machine without any intermediate media:
cd dir; tar cf - . | rsh remote_machine "cd dir2; tar xvpf -"
A NeXT consultant showed me this:
mv /some/long/path/{old,new}file.blah
The {,} notation expands the containing word to a space-separated list obtained by substituting in each thing in the {}, giving for the above:
mv /some/long/path/oldfile.blah /some/long/path/newfile.blah
Great for mv, cp, ln, diff, cmp.
Free On-Line Dictionary of Computing http://foldoc.org/
Using pipes is one of the most useful things I've found.
In my signature, a simple HEADER checker:
Testing your microphone input:
Harassing someone by sending your mic input to their soundcard output:
Back up something over the network to a file.
Decompress something that you don't have the space to do on either server or computer, or just don't want to waste time.
A few non-pipe related tips:
Wine prefixes - a method to create unique Wine directories to separate local 'wine' setups.
If you ever have a game crash, you may have noticed that X doesn't automatically switch back to your default resolution, this can be done with:
Hope this was useful to someone.
Change is certain; progress is not obligatory.
Suppose you did this: ls -la filename, then you can do this: man !:0 which converts the !:0 into the zeroth word on the previous command, namely ls. So man !:0 would be man ls. Similarly, !:1 changes to -la, and !:2 is filename. You may also like !:1* or !:2*. !:1* would be the first word and all after it, !:2* is the second word and all after it. So !:1* changes to -la filename in this case. There is also !:0-2 for a range of words. Here is an example:
More information can be found in the HISTORY EXPANSION section of the bash manpage. Specifically, the Word Designators subsection. Enjoy!
(Some of these might have been mentioned)
Bash foo:
# Make my prompt "pretty" colours and set the xterm title bar to useful things at every command. Also make the continuation prompt blue rather than '> ' so I can cut and paste
PS1='\[\033[00;31m\]$USER\[\033[00;33m\]@\[\033[00;32m\]\h\[\033[00;00;00m\]:\[\033[00;34m\]\w\[\033[00;00;00m\]\$ '
PS2='\[\033[00;34m\]'
# Tell me if something worked
random_command && echo yes || echo no
# Completions:
# commands which should complete to a command
complete -A command which
# commands which should complete to a shell variable
complete -A file -A variable unset
complete -A file -A variable export
# commands which should complete to a word list and files
complete -A file -W "commit diff remove update status annotate log" cvs
complete -A file -W "all install depend clean" make
complete -A file -W "all install depend clean" pmake
# C-d twice to log out
IGNOREEOF=1
# Avoid tmp files
join <(sort file1) <(sort file2)
# Other things
shift-insert to paste from the clipboard in terminals
history > ~/docs/stuff_i_just_did_so_i_dont_forget
less -S for wide files
strace / ptrace / truss
pushd/popd
--oik
sudo !!
Repeats your previous command as the root user.
Very useful if you typed out a big long command, but forgot to run it as root.
-- If you try to fail and succeed, which have you done? - Uli's moose
find and xargs is an absolutely brilliant combination. I can't live without it.
find . -type f -print0 | xargs -P 4 -0 echo grep -H WHATEVER
searches for the string WHATEVER in all regular files, weird-filename-safe. xargs runs 4 parallel greps, to make use of all those CPUs and cores! Here's two test runs, note the changing order:
$ find . -type f -print0 | xargs -P 5 -n 2 -0 echo grep a ./1 ./2 ./5 ./6 ./7 ./8 ./3 ./4 ./9 ./1 ./2 ./3 ./4 ./5 ./6 ./7 ./8 ./9
grep a
grep a
grep a
grep a
grep a
$ find . -type f -print0 | xargs -P 5 -n 2 -0 echo grep a
grep a
grep a
grep a
grep a
grep a
cleartool ci -nc `cat`
A pipe (as I hint at elsewhere) through while ... read would reduce that:
cleartool lsco -cview -me -r -s | while read FILE ; do cleartool ci -nc ${FILE} ; done
Comment removed based on user account deletion