Unix terminal, a simple cheatsheet

Unix terminal is a powerful tool.
I think that a lot of tasks (including my own forensics analysis workflows) can be accomplished more quickly on a “terminal only” environment.

Here my brief cheatsheet with useful commands and tips.

Reload shell without exit
exec $SHELL -l

Close shell keeping all subprocess running
disown -a && exit

Exit without saving shell history
kill -9 $$
unset HISTFILE && exit

Perform a branching conditional
true && { echo success;} || { echo failed; }

Pipe stdout and stderr to separate commands
some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr)

Redirect stdout and stderr each to separate files and print both to the screen
(some_command 2>&1 1>&3 | tee errorlog ) 3>&1 1>&2 | tee stdoutlog

List of commands you use most often
$ history | awk '{print $2}' | sort | uniq -c | sort -rn | head

Quickly rename a file
$ mv filename.{old,new}

Simply backup a file adding “.bak” extension
cp filename{,.bak}

Empty a file
>filename

Delete all files in a folder that don’t match a certain file extension
rm !(*.foo|*.bar|*.baz)

Add a multi-line string to a file
cat > filename << __EOF__
data data data
__EOF__

Edit a file on a remote host using vim
vim scp://[email protected]//etc/fstab

Create a directory and change into it at the same time
mkd () { mkdir -p "[email protected]" && cd "[email protected]"; }

Convert uppercase files to lowercase files
rename 'y/A-Z/a-z/' *

Print a row of characters across the terminal
printf "%`tput cols`s" | tr ' ' '#'

Put a console clock in top right corner
$ while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-29));date;tput rc;done &

Show shell history without line numbers
history | cut -c 8-
fc -l -n 1 | sed 's/^\s*//'

Execute a command without saving it in the history
$ <space>command

Run command(s) after exit session

Add this code to /etc/profile (for system wide) or ~/.bashrc for local profile:

_after_logout() {

  username=$(whoami)

  for _pid in $(ps afx | grep sshd | grep "$username" | awk '{print $1}') ; do

    kill -9 $_pid

  done

}
trap _after_logout EXIT

Generate a sequence of numbers
Using seq:
    seq 1 2 10

Without seq:
   for ((i=1; i<=10; i+=2)) ; do echo $i ; done

Run the last command
$ !!

Run the last command as root
$ sudo !!

Create a script of the last executed command
$ echo "!!" > script.sh

Reuse all parameter of the previous command line
$ echo cd .
$ !*

Run the last command with some argument
$ echo a b c d e
$ echo !!:2
$ echo !!:3-$

Insert the last argument of the previous command
$ cp script.sh /usr/bin/
$ cd <ESC> .

Run previous command but replacing
$ echo no tobereaplaced
$ ^tobereaplaced^replaced

Avoid any command aliases
$ alias ls="rm -rf /"
$ \ls

 

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.