Miscellaneous - Command Line Kung Fu (2014)

Command Line Kung Fu (2014)

Miscellaneous

Change to the Previous Working Directory

$ cd -

If you want to return your previous working directory, use "cd -". The OLDPWD environment variable holds the path of your most recent directory location. "cd -" is the same as "cd $OLDPWD".

$ cd /etc/httpd/conf.d

$ grep ^SSLCert ssl.conf

SSLCertificateFile /etc/pki/tls/certs/localhost.crt

SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

$ cd /etc/pki/tls/certs/

$ ls

ca-bundle.crt ca-bundle.trust.crt localhost.crt make-dummy-cert Makefile renew-dummy-cert

$ cd -

/etc/httpd/conf.d

$

Reset Your Terminal Emulator Display

$ reset

Displaying binary files to your screen can cause your terminal to become unusable. To attempt to recover, type "reset" and press enter. Your terminal may be in such a state that you won't be able to see what you're typing, but you shell will still accept the input.

$ cat blue-train.mp3

F���A������h�reset

$

Search Wikipedia from the Command Line

$ dig +short txt <string>.wp.dg.cx

$ host -t txt <string>.wp.dg.cx

If you need to quickly look up some information on a subject, you can search wikipedia using DNS. The name server returns wikipedia article summaries as TXT records.

$ dig +short txt linux.wp.dg.cx

"Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of Linux is the Linux kernel, an operating system kernel first released 5 October 1991 by Linus Torvalds. http://en.wikipedia.org/wiki/Linux"

$ host -t txt bash_shell.wp.dg.cx

bash_shell.wp.dg.cx descriptive text "Bash is a Unix shell written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell (sh).Bash is a command processor, typically run in a text window, allowing the user to type commands which cause actions. Bash can also read commands from a file, called a script. Like all Unix shells, it supports filename wildcarding, piping, here documents... http://en.wikipedia.org/wiki/Bash_(Unix_shell)"

You can create a small shell script to save yourself from typing the full DNS query each time.

$ echo -e '#!/bin/bash\ndig +short txt ${1}.wp.dg.cx' > wikidig

$ chmod 755 !$

chmod 755 wikidig

$ ./wikidig ubuntu_operating_system

"Ubuntu As of 2012, according to online surveys, Ubuntu is the most popular Linux distribution on desktop/laptop personal computers, and most Ubuntu coverage focuses on its use in that market. However, it is also popular on servers and for cloud computing. http://en.wikipedia.org/wiki/Ubuntu_(operating_system)"

Alternatively, you could create a function instead and add it to your dot files.

$ echo 'wikidig() { dig +short txt ${1}.wp.dg.cx; }' >> .bash_profile

$ . ~/.bash_profile

$ wikidig jazz

"Jazz is a musical style that originated at the beginning of the 20th century in black communities in the Southern United States. It was born out of a mix of African and European music traditions. Its African pedigree is evident in its use of blue notes, improvisation, polyrhythms, syncopation and the swung note. From its early development until the present day jazz has also... http://en.wikipedia.org/wiki/Jazz"

Make Non-Interactive Shell Sessions Behave the Same as Interactive Sessions

Make any customizations in ~/.bashrc. The contents of ~/.bash_profile:

if [ -f ~/.bashrc ]; then

source ~/.bashrc

fi

The shell behaves in slightly different ways when you log on interactively versus when you just connect to run a single command. The contents of .profile or .bash_profile are only executed for interactive sessions. If you are not aware of this subtle difference it may leave you scratching your head as to why something works perfectly when you log in and execute a command versus when you just ssh in to run that same command. You can save yourself some hassle by making your interactive and non-interactive sessions behave the same. To do this, configure .bash_profile to reference .bashrc and put all of your configuration in .bashrc.

Here is an example to better illustrate the difference between interactive and non-interactive shells. For example, if you define an alias for ll in ~/.bash_profile it will work during an interactive session but it will not be available during a non-interactive session.

Interactive:

mac:~ jason $ ssh linuxserver

jason@linuxserver:~$ uptime

11:49:16 up 97 days, 2:59, 5 users, load average: 0.15, 0.25, 0.31

jason@linuxserver:~$ ll

-rw-r--r-- 1 jason jason 221 Nov 13 11:30 file.txt

jason@linuxserver:~$ exit

logout

Connection to 10.0.1.9 closed.

mac:~ jason $

Non interactive:

mac:~ jason$ ssh linuxserver uptime

11:49:16 up 97 days, 2:59, 5 users, load average: 0.15, 0.25, 0.31

mac:~ jason$ ssh linuxserver ll

bash: ll: command not found

mac:~ jason$

$ cat .bash_profile

# Put our settings in .bashrc so we have the same environment for login and non-login shells.

if [ -f ~/.bashrc ]; then

source ~/.bashrc

fi

$ cat .bashrc

alias ll='ls -l'

HISTFILESIZE=5000

export HISTFILESIZE

Make Your Computer to Talk to You

$ espeak -f file

$ echo text | espeak

Espeak converts text to speech. You can provide espeak a file or pipe in text for it to speak. If you have a long running task you can let your computer tell you when it's finished as in this example.

$ for VIDEO in $(ls *.mp4 | sed 's/.mp4//')

> do

> avconv -v quiet -i $x.mp4 $x.mp3

>done ; echo "File conversions complete." | espeak

Display the Current Date and Time in a Different Time Zone

$ TZ=<TIMEZONE> date

The TZ environment variable specifies the time zone. If you want to know the time in a given time zone, prepend the environment variable and time zone to the date command.

$ TZ=America/Los_Angeles date

Sun Apr 6 19:37:46 PDT 2014

$ TZ=MST date

Sun Apr 6 19:37:48 MST 2014

$ TZ=CST date

Mon Apr 7 02:37:50 CST 2014

$ TZ=UTC date

Mon Apr 7 02:37:53 UTC 2014

It's a common practice to use UTC as the time zone on servers. If your workstation or laptop is set to a different time zone, you can create an alias that quickly gives you the time in UTC.

$ alias utc='TZ=UTC date'

$ utc

Mon Apr 7 02:35:01 UTC 2014

Display a Calendar at the Command Line

$ cal

$ cal MM YYYY

$ cal YYYY

To display an calendar at the command line use the cal command. Use the -3 option to display the previous, current, and next month. If you want to see the calendar for an specific month use MM YYYY or for an entire year use YYYY.

$ cal

April 2014

Su Mo Tu We Th Fr Sa

1 2 3 4 5

6 7 8 9 10 11 12

13 14 15 16 17 18 19

20 21 22 23 24 25 26

27 28 29 30

cal-3.png

$ 10 2014

October 2014

Su Mo Tu We Th Fr Sa

1 2 3 4

5 6 7 8 9 10 11

12 13 14 15 16 17 18

19 20 21 22 23 24 25

26 27 28 29 30 31

Extract a Tar Archive to a Different Directory

$ tar tarfile.tar -C /path/to/extraction/directory

Instead of changing directories and untarring a file, you can use the -C option.

$ tar xf projectfiles.tar -C /usr/local/myproject

This is equivalent to these two commands.

$ cd /usr/local/myproject

$ tar xf ~/projectfiles.tar

Transform the Directory Structure of a Tar File When Extracting It

$ tar xf tarfile.tar --strip-components=NUMBER

If you want to extract a tar file starting at a subdirectory, use the --strip-components option. For example, if you download a release from github.com the name and version of the project is the top directory in the tar file. To extract the files below that directory use --strip-components=1.

$ curl -sLO https://github.com/twbs/bootstrap/archive/v3.1.1.tar.gz

$ tar ztvf v3.1.1.tar.gz | head -1

drwxrwxr-x root/root 0 2014-02-13 12:24 bootstrap-3.1.

$ tar zxvf v3.1.1.tar.gz --strip-components=1 -C ~/bootstrap-latest

$ ls -1 ~/bootstrap-latest

bower.json

CNAME

composer.json

_config.yml

CONTRIBUTING.md

dist

docs

fonts

grunt

Gruntfile.js

js

less

LICENSE

package.json

README.md

test-infra

Use a Spreadsheet from the Command Line

$ sc

If you're the kind of person that tries to do absolutely everything at the command line, then you'll like the spreadsheet calculator, SC. Also, if you're comfortable with vi, then sc will come naturally to you. In addition to using the arrow keys for navigation you can use the familiar h, j, k, and l keys. Like vi, g represents go. To go the cell D4 type gD4.

To enter a number or a formula navigate to the cell you want to edit and use = followed by the number or formula. To enter left justified text use the less-than sign (<) and the greater-than sign (>) for right justified text. To edit a cell type e. To save a file, press P followed by a filename. For quick help type ? and to quit, type q. For more information check out the tutorial that ships with SC.

$ sc

A2 (10 2 0) [@sum(A0:A1)]

A B C

0 1.00

1 3.00

2 4.00

$ sc /usr/share/doc/sc/tutorial.sc

Rudimentary Command Line Stopwatch

$ time read

This command will stop when you press enter and display how much time elapsed. The real row contains the elapsed time.

$ time read

real 0m8.047s

user 0m0.000s

sys 0m0.000s

$

Repeat a Command at Regular Intervals and Watch Its Changing Output

$ watch command

If you want to monitor the output of a command, use watch. Watch will execute a command periodically and display its output. You can control the interval that the command is repeated by supplying a number of seconds to the -n option. This is great tool to watch processes, disk usage, number of logged in users, queue depths, etc.

$ sudo /usr/local/bin/compress-log-files &

[1] 15650

$ watch df -h /var

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_livecd-lv_root 28G 3.7G 24G 14% /

...

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_livecd-lv_root 28G 3.3G 25G 12% /

$ watch -n 1 "ps -ef| grep httpd | grep -v grep | wc -l"

9

14

29

27

$

Execute a Command at a given Time

$ echo "command" | at time

$ at -f file time

If you ever need to reboot a server at midnight, but don't feel like staying up that late, schedule it with the at command. Actually you can schedule any command or set of commands that you need to run once at a given time with at. To list your at jobs use atq. Here's the reboot example.

$ sudo -s

# echo 'reboot' | at midnight

# atq

1 2014-04-13 00:00 a root

# exit

$ exit

You can provide at with a series of commands in a file by using the -f option. For example, you could send your boss a report at 5:00 PM on Friday and leave early to play a round of golf. If your conscience gets the better of you, you can delete your at job with atrm.

$ at -f email-tps-report-to-boss 5:00pm friday

job 2 at 2014-04-18 17:00

$ atrm 2

$ atq

$

Share Your Screen Session with Another User

$ screen -x user/session

In order to use multi user support for screen, the screen executable needs to be setuid for root.

$ sudo chmod u+s /usr/bin/screen

One user must start a screen session. It can be helpful to name your screen sessions with the -S option. To enable multi user session, type ctrl-a followed by ":multiuser on<enter>". To allow someone to connect to your session type ctrl-a followed by ":acladd username". To disconnect the other user from the screen session type ctrl-a followed by ":acldel username".

[jason@linuxsvr ~]$ screen -S for-bob

ctrl-a :multiuser on

Multiuser mode enabled

ctrl-a :acladd bob

When the other use is ready to connect to the screen session, they type screen -x followed by the session identifier. They can connect by PID or by name. IE, screen -x 1234 or screen -x session-name. When they are ready to disconnect, they can leave the screen session like any other by typing ctrl-a d. While the session is shared both parties not only can they see the same screen, but they both provide input by typing.

bob@linuxsvr:~$ screen -ls jason/

There is a suitable screen on:

5428.for-bob (Multi, attached)

1 Socket in /var/run/screen/S-jason.

bob@linuxsvr:~$ screen -x jason/for-bob

[jason@linuxsvr ~]$

ctrl-a d

[detached]

bob@linuxsvr:~$

Execute an Unaliased Version of an Aliased Command

$ \aliased-command

Use the escape character to ignore an alias for a command. For example, if "ls" is aliased to "ls -F", use "\ls" to execute "ls" without the "-F" option. The "-F" option to ls appends a file type indicator. In the case of directories that indicator is a forward slash (/).

$ alias ls

alias ls='ls -F'

$ ls

Desktop/ Documents/ Downloads/ examples.desktop

$ \ls

Desktop Documents Downloads examples.desktop

$

Save the Output of a Command as an Image

$ command | convert label:@- image.png

To capture the output of a command in an image file, use the convert command from the ImageMagick software suite. If you want to email a password to someone, but don't want it travel around the Internet in plain text, put it in an image. When supplying the at sign (@) to label it tells convert to read input from the file following the at sign. The dash says the "file" is coming from standard input. If you want to create a simple image with some text you can supply a string to label.

$ echo "bob:changeme" | sudo chpasswd

$ echo "bob:changeme" | convert label:@- password.png

$ convert label:"bob:changeme" same-thing-different-way.png

$ echo "Here's your password. Again." | mail -a passwd.png -s 'Password reset' bob@mycompany.com

$