Ubuntu/Linux cmd-line Cheat Sheet
Tags: bash, ubuntu, linux
Published: 2020-08-16 16:20:06

#####*[Originally posted on Codepen Oct 30, 2015](https://codepen.io/write/bash-cheat-sheet2)*
  
#### Convert binary, hex, or any base, into decimal

from hex to decimal: `$((16#62)) => 98` (note the `16#`)
from binary to decimal: `$((2#01110011)) => 115` (note the `2#`)
**Note**: the expression `$(())` will execute a command named according to what it returns, so `echo` it to avoid the prompt complaining that it knows no command named `98` or `115`
```
picoplayer@challenge:~$ $((16#62))
98: command not found
picoplayer@challenge:~$ echo $((16#62))
98
```
 
#### Convert ASCII hex value into the actual characters
**note**: also works with `0x` prefix, ie: `0x62 0x64 0x61 0x36 0x38 0x66 0x37 0x35`
```
$ echo "62 64 61 36 38 66 37 35" | xxd -p -r
bda68f75
``` 
#### Convert to text from [binary|octal|hex]
```
$ x="01100011 01101111 01101101 01110000 01110101 01110100 01100101 01110010"
$ for a in $x; do printf "%x" $((2#$a)); done | xxd -r -p && echo " "
computer
$ x="160 145 141 162"
$ for a in $x; do printf "%x" $((8#$a)); done | xxd -r -p && echo " "
pear
$ x="66616c636f6e"
$ for a in $x; do printf "%x" $((16#$a)); done | xxd -r -p && echo " "
falcon
$
```

#### Convert character into decimal ASCII value
```
$ printf "%d\n" "'a"
97
```

#### Convert decimal ASCII value into a character
```
$ printf "%x" 97 | xxd -r -p
a
```

#### Convert decimal ASCII value into hex value
```
$ printf "%x" 97
61
```
#### List sudo available commands: `sudo -l`

#### Bypassing permissions 
As can be seen in the output below, the `challenge` directory is not accessible since no permissions have been set (`0 d---------    1 root   root     27 Aug  4 21:34 challenge`).

```
picoplayer@challenge:~$ cd /
picoplayer@challenge:/$ ls -ls

total 0
0 lrwxrwxrwx    1 root   root      7 Mar  8  2023 bin -> usr/bin
0 drwxr-xr-x    2 root   root      6 Apr 15  2020 boot
0 d---------    1 root   root     27 Aug  4 21:34 challenge
0 drwxr-xr-x    5 root   root    340 Dec 13 17:55 dev
0 drwxr-xr-x    1 root   root     66 Dec 13 17:55 etc
0 drwxr-xr-x    1 root   root     24 Aug  4 21:32 home
0 lrwxrwxrwx    1 root   root      7 Mar  8  2023 lib -> usr/lib
0 lrwxrwxrwx    1 root   root      9 Mar  8  2023 lib32 -> usr/lib32
0 lrwxrwxrwx    1 root   root      9 Mar  8  2023 lib64 -> usr/lib64
0 lrwxrwxrwx    1 root   root     10 Mar  8  2023 libx32 -> usr/libx32
0 drwxr-xr-x    2 root   root      6 Mar  8  2023 media
0 drwxr-xr-x    2 root   root      6 Mar  8  2023 mnt
0 drwxr-xr-x    2 root   root      6 Mar  8  2023 opt
0 dr-xr-xr-x 2501 nobody nogroup   0 Dec 13 17:55 proc
0 drwx------    1 root   root     23 Aug  4 21:34 root
0 drwxr-xr-x    1 root   root     54 Dec 13 17:56 run
0 lrwxrwxrwx    1 root   root      8 Mar  8  2023 sbin -> usr/sbin
0 drwxr-xr-x    2 root   root      6 Mar  8  2023 srv
0 dr-xr-xr-x   13 nobody nogroup   0 Dec 13 17:55 sys
0 drwxrwxrwt    1 root   root      6 Aug  4 21:34 tmp
0 drwxr-xr-x    1 root   root     18 Mar  8  2023 usr
0 drwxr-xr-x    1 root   root     17 Mar  8  2023 var
```

So the idea, is to use `vi` to access the contents of the `challenge` directory anyway, because as seen in the last line of the following output, `vi` can be used with `sudo`

```
picoplayer@challenge:/$ sudo -l
Matching Defaults entries for picoplayer on challenge:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User picoplayer may run the following commands on challenge:
    (ALL) /usr/bin/vi
```

So, finally:
1. type `sudo vi`, 
1. type `:! ls -ls /challenge/`
1. read the following output

```
picoplayer@challenge:/$ sudo vi
[sudo] password for picoplayer: 

4 ---------- 1 root root 98 Aug  4 21:34 metadata.json
```

I now even can print the contents of that file.  So, still from vi, type `:! cat /challenge/metadata.json`

#### Convert string to MD5 hash
```
# to avoid the trailing newline added by the shell: '%s'
printf '%s' "money" | md5sum
```

#### Determining the contents of non-text files, like a binary file for example.
```
strings -a -t x [path-to-binary-file-for-example]
```

#### Create a binary (executable) file from a bash script ([install shc](https://www.geeksforgeeks.org/shell-scripting-creating-a-binary-file/))
```
# This will create 2 files, and the binary/exec one is 'add.sh.x'
shc -f add.sh
```

#### View contents of binary file
```
# bvi, bview - visual editor for binary files
bvi ./add.sh.x
```

#### Is package installed?
```
dpkg -s gimp
```

#### Update all packages at once
Disclaimer: this command should probably never be used in an actual production server ;)
```
sudo apt-get install -f
```

#### Free port
```
kill $(lsof -t -i:3000)
```

#### LAN Access for WSL localhost
These are Powershell (run as admin) commands. ([source1](https://superuser.com/questions/1586386/how-to-find-wsl2-machines-ip-address-from-windows) | [source2](https://stackoverflow.com/questions/61002681/connecting-to-wsl2-server-via-local-network))
```
netsh advfirewall firewall add rule name="Allowing connections to WSL2 servers" dir=in action=allow protocol=TCP localport=3000

netsh interface portproxy add v4tov4 listenport=3000 listenaddress=0.0.0.0 connectport=3000 connectaddress=[plug here the result of `wsl hostname -I`]
```
##### To show added rule & proxy
```
netsh advfirewall firewall show rule name="Allowing connections to WSL2 servers"

netsh interface portproxy show v4tov4
```


#### Install a package (.deb)
```
sudo dpkg -i /path/to/deb/file
```

#### create a tree of directories in one command

```
mkdir -pv dir1/dir2/dir3/dir4/dir5
```
The above commands will create directory(s) recursively inside a non-existent directory(s). You can use the 'tree' command to view the directory structure.

```
tree dir1/
```
```
dir1/
└── dir2
 └── dir3
 └── dir4
 └── dir5
4 directories, 0 files
``` 
#### Find files recursively in all subdirectories and list them by DESC file size
```
ls -lhR | grep -E "\.(jpg|zip)$" | awk '{print $5, $9}' | sort -hr
```
Or,
```
find . -type f -exec du -h {} + | grep -E "\./.*\.(jpg|zip)" | sort -hr
```

#### Find files by name in a directory tree
This search is case insensitive (-ipath) and recursively traverses the all subdirectories.
The path
```
find -ipath */ubeR-secret.txt
``` 
Output:
```
./adequate_books/more_books/.secret/deeper_secrets/deepest_secrets/uber-secret.txt
```

#### Using command output as the parameter of another command
Just place it between `$([command])`.
I should call that this works because I'm expecting a single result in the output.  Unexpected results might happen if cat (or the encapsulating command) was fed a multiline result as parameters...
```
cat $(find -ipath */ubeR-secret.txt)
```

#### List files that were created between 2 dates

```
find . -type f -newermt "2012-01-01" \! -newermt "2020-09-01"
```

#### Search for file contents in a directory tree recursively

```
grep -r "pico"
```

Output:

_big-zip-files/folder_pmbymkjcya/folder_cawigcwvgv/folder_ltdayfmktr/folder_fnpfclfyee/whzxrpivpqld.txt:information on the record will last a billion years. Genes and brains and books encode **pico**CTF{gr3p_15_m4g1c_ef8790dc}_





#### make script file executable
```
chmod +x [filename]
```

#### Get local IP address
```
hostname -I | awk '{print $1}'
``` 

#### Open current terminal location into file explorer

```
xdg-open file
```


#### Download file to current directory, using the name and extension found in the URL

```
wget https://raw.githubusercontent.com/ariya/phantomjs/master/examples/printenv.js
```

#### Create a symbolic link

```
ln -s /path/to/original /path/to/symlink
```

#### Saving as unix file from VIM

```
:set fileformat=unix
```

#### Find what PID is locking a port

```
netstat -tulpn | grep <port>
```

#### Force kill a PID

```
kill -9 <PID>
```

#### Find out what process is locking a file

```
fuser <file_path>
```

#### Avoid being prompted for private key when using SSH or scp to connect to hosts with your public key.

 ```
 eval `ssh-agent`
 ```
 
 ```
 ssh-add
 ```

#### Command to kill a UI/Desktop Application

```
xkill
```

#### Terminator preferences profile (~/.config/terminator/config)

```
[global_config]
[keybindings]
[profiles]
  [[default]]
    use_system_font = False
    background_image = None
    background_darkness = 0.91
    active_encodings = ANSI_X3.4-1968, UTF-8, ISO-8859-1
    foreground_color = "#839496"
    font = Ubuntu Mono 14
    background_color = "#002b36"
    scrollback_infinite = True
[layouts]
  [[default]]
    [[[child1]]]
      type = Terminal
      parent = window0
    [[[window0]]]
      type = Window
      parent = ""
[plugins]
```

#### My custom bash prompt

```
########### current_dir(current_git_branch) ####################
parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
 
RED="\[\033[0;31m\]"
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
NO_COLOR="\[\033[0m\]"
 
PS1="$GREEN\W$YELLOW\$(parse_git_branch)$NO_COLOR "
####################
```


#### Cancel reverse-i-search

```
Ctrl+G
```

#### Activate reverse-i-search

```
Ctrl+R
```


#### Reload bash prompt after **.bashrc** modification

```
source .bashrc
```


#### Google chrome path

```
which google-chrome
```

#### Check ubuntu version

```
lsb_release -a
```

#### Make umount Work with sshfs

```
fusermount -u /path/to/mounted-dir
```

#### Get a report of the used and available space on all mounted drives

```
df -h
```

#### Get a report of the size of data by folder

```
sudo du -sk /home/* > tmp3.txt
```

#### Sort report

```
sort -n tmp.txt
```

#### Get a list of processes, ssh in this case

```
ps -ax | grep ssh
```


#### Print number of **.tpl** files (from current directory and in all nested directories..)

```
find -name '*.tpl' | wc -l
```


#### Print a list of **.tpl** files (from current directory and in all nested directories..)

```
find -name '*.tpl'
```


#### Look for the number of files (.tpl in this case) per directory

```
 for D in *; do echo $D; find $D -type f -name '*.tpl'| wc -l; done
```