Command Line Tips and Tricks

From Notes

Jump to: navigation, search

When you try to logout of an SSH session and the session hangs, try the following to terminate it:

~.

...that is, [Shift-backtick] then [period].


(BASH) To use the last argument of the previous command as the argument to this command, try the following:

ls /tmp
cd !$

The previous example lists the contents of the /tmp directory, then uses the cd command to change directory to that location.

You can also use any argument from the previous command by using !:x, where x is the index of the argument (base 0).


Obtain the PID of the shell that you are in:

echo $$

Use ionice to reduce the priority of IO for a specific PID (great when used with the previous tip for a complete shell):

ionice -c3 -p$$

awk tips

Print matching line and following line(s):

awk '/<match string>/ {print $0; getline; print $0;}' file.txt

In the previous command, after the match is found, the getline function is used to advance to the next line, where another print is used to print the next line.


Single ticks vs quotes for variables

In order to pass the value of a variable to a command like awk or some ldap commands (among others) it is necessary to use single quotes to send commands or values to awk, then use double quotes to enable the shell to interpret the variable. One example is as follows:

export VALUE=CPU
dmesg | awk '/'"${VALUE}"'/ {print}'

The above example would assign the value of CPU to a variable VALUE. The next command would call awk, passing into awk the variable VALUE, using single and double quotes to interpret the variable and pass that value to awk.