A small list of command line tips

Updated: 2014 May 14th; added even more tips

I'm in the middle of writing papers and my thesis, so I've been quite busy. However, I wanted to write a quick blog post as an outlet. So here's a list of random command line tips off the top of my head (GNU bash, version 4.1.2(1)-release); I hope that there's at least one tip in this list you didn't know about beforehand.

The find tool is extremely useful; some uses include:

#in all Perl files
#execute a grep quietly
#and look for human_id
#then report which file contains a match
find . -name '*.pl' -exec grep -q 'human_id' {} \; -print

#find broken symbolic links and delete them
find -L . -type l -delete

Randomly shuffle lines using shuf:

for i in {1..10}; do echo $i; done | shuf
9
10
5
2
8
3
4
6
1
7

Use the -A and -B parameters of grep to print the lines before and after your matched line.

#echo out a bunch of lines
echo -e "3\n2\n1\nA\n1\n2\n3"
3
2
1
A
1
2
3

#show me two lines before and two lines after A
echo -e "3\n2\n1\nA\n1\n2\n3" | grep -B2 -A2 A
2
1
A
1
2

#also use -E with grep for extended regular expressions
#Basic vs Extended Regular Expressions
#       In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the #backslashed versions \?, \+, \{, \|, , and .
#
#       Traditional egrep did not support the { meta-character, and some egrep implementations support \{ instead, so portable #scripts should avoid { in grep -E patterns and should use [{] to match a literal {.
#
#       GNU grep -E attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid #interval specification.  For example, the command grep -E '{1' searches for the two-
#       character string {1 instead of reporting a syntax error in the regular expression.  POSIX.2 allows this behavior as an #extension, but portable scripts should avoid it.

Use watch to run a command every 2 seconds (default is 2 seconds):

#monitor the contents of a folder
#this can be useful for monitoring output files
watch ls -lt

#monitor the statuses of UGE hosts
watch qhost

#other monitoring tips
#use "tail -f" to monitor a file if it is growing
tail -f /var/log/apache/access.log

#check out the last 10 users who have logged into a server
last | head

Continue reading