Friday, August 8, 2008

Bash One-Liners

To tar and gzip in one line (if -z option is not available, like on HP-UX.)
# Compress and Tar
$ tar cvf -  | gzip -c > tgzfile.tar.gz

# Untar and Decompress
$ gzip -dc tgzfile.tar.gz | tar xvf -
To search and replace in multiple files,
perl -pi -w -e 's/search/replace/g;' *.html

     -e means execute the following line of code.
     -i means edit in-place
     -w write warnings
     -p loop
To convert multiple JPEG files into one PDF file, first, install ImageMagick, then run:
convert *.jpg -adjoin [file].pdf

To repeat the last command entered, except with sudo prepended to it, run:
$ sudo !!

Redirect output to file with sudo
$ sudo bash -c "echo 'Hello world' > helloworld.txt"
# -OR-
$ echo "Hello world | sudo tee helloword.txt

To find out CPU / memory information
$ cat /proc/cpuinfo
$ cat /proc/meminfo

To find out diskspace
$ df -h

A command that returns value of a symbolic link or canonical file name.
$ readlink /etc/localtime
/usr/share/zoneinfo/America/Los_Angeles

'awk' command examples:
# Print username with ':' as field-separator, -F fs --field-separator=fs
$ awk -F: '{ print $1 }' /etc/passwd

# Calculate the sum of the first column in file
$ awk '{ sum += $1 }; END { print sum }' file

# Reverse a list of arguments
$ echo 'col1 col2 col3' | awk '{ print $3, $2, $1 }'
col3 col2 col1

$ echo 'col1:col2:col3' |awk -F: '{ print $3 ":" $2 ":" $1}'
col3:col2:col1

Check if a process is running, e.g. httpd
$ ps ax | grep -v grep | grep httpd
$ ps ax | grep -v grep | grep httpd > /dev/null && echo 'httpd is running.'
# OR
$ ps ax | grep -v grep | grep httpd > /dev/null || echo 'httpd is not running.'