my-command
Cheatsheets
Compile C
gcc -o caesar caesar.c -lcs50
Get all branch of repository
git fetch --all && git pull origin '*:*'
Install the download package
sudo dpkg -i package.deb
Display or Check SHA256 checksum
Display and check hash of a file or text
SHA256
- display hash of a sample text "Hello, world"
echo Hello, world| sha256sum
OR
printf Hello, world | sha256sum
- check hash of ubuntu downloaded
cd download_directory && sha256sum ubuntu-9.10-dvd-i386.iso
KECCAK-256 (SHA-3)
printf Hello, world | openssl dgst -sha-256sum
Google Colab
- use from file in google colab
from google.colab import drive drive.mount('/content/drive/')
Tmux
Activation | Command |
---|---|
Zoomin window | Ctrl + b z |
Zoomout window | Ctrl + b z |
Vertical division window | Ctrl + b % |
Horizontal division window | Ctrl + b " |
Close a window | Ctrl + b x |
Close all windows (close tmux) | Ctrl + b & |
Resize winddows | Ctrl + b ⭠ ⭡ ⭣ ⭢ |
Show Time | Ctrl + b t |
Number of windows | Ctrl + b q |
Zellij
Activation | Command |
---|---|
Zoomout window | Ctrl + b + z |
Vertical division window | Ctrl + b + % |
Horizontal division window | Ctrl + b + " |
Close a window | Ctrl + p + x |
Switching bitween windows | Ctrl + b + ⭠ ⭡ ⭣ ⭢ |
Switching bitween windows | Alt + ⭠ ⭡ ⭣ ⭢ |
Resizing window | Ctrl + n + ⭠ ⭡ ⭣ ⭢ |
Rename window | Ctrl + p + c |
Manager | Ctrl + o + w |
Change Horizontal/Vertical windows | Ctrl + Space |
Floating window | Alt + f |
Resize window |
Vim
Description | Command | Description |
---|---|---|
Copy mode | Ctrl + v |
|
Copy | " + + + y |
|
Pase | " + + + p |
|
Write on the previuse line | Shift + o |
for open a line before |
Write on the next line | o |
for open a line after |
Append | Shift + a |
for append text in end line |
Append | a |
for append text after next character |
Delete word | d + w |
for delete word |
Delete line | d + $ |
for delete line |
Delete line (cut) | d + d |
for delet line (all) |
Move word | w |
for move on the beginning of words |
Move word | b |
Backward to start of current/previous word |
Move word | e |
for move on the ends of words |
Start line | 0 |
for move on the beginning of lines |
End line | $ |
for move on the ends lines |
Delete multi word | 5 + d + w |
for delete 5 words |
Undo | u |
for undo one by one |
Undo | Shift + u |
for undo |
Redo | Ctrl + r |
for redo |
Replace | r |
for replace a letter |
Correct | ce or cw or c$ or ... |
ce :Correct and replace untile end of word. c$ : Correct from the word until end of the line. |
Show file info | Ctrl + g |
Show file name, lines and ... |
End of the file | Shift + g |
go to end file |
Start of the file | g + g |
go to start file |
Go to line n | n + Shift + g |
Go to line n (n is a natural number) |
Search | / |
For search in forwqrd |
Search | ? |
for search in backward |
Next | n |
next finded |
Previous | Shift + n |
previous finded |
Find maches | % |
find maches parantesis or brocets or ... |
- Substitude
:[range]s/pattern/replacement/[flags]
- [range]
%
-> All content10, 20
-> Line 10-20
- pattern -> RegEx
- replacement -> text
-
[flags]
g
-> All selected by patternc
-> Accept for each replace (confirm)
-
for example: replace foo inestead of bar on all content
vim:%s/bar/foo/g
Customize vim
Git
git clone <repo-url> cd <repo> git fetch --all for branch in $(git branch -r | grep -v '\->');do git branch --track "${branch#origin/}" "$branch"; done
- To push all branches
git push --all origin
OR
git push origin branch1 branch2 branch3 ...
- To commit on the latest commit
git add . git commit --amend --no-edit
- Show graphically git log
git log --all --decorate --online --graph
- Get spesific branch from repo
git clone --branch=main https://github.com/username/repo.git
- Get spesific commits from repo (for example 01 last commit)
git clone --depth 10 https://github.com/username/repo.git
- Local clone repository (from this path to another path locally)
git clone repo_path
- Show changes by HEAD commit
git diff
OR
git diff HEAD
- Show changes from the last commit with 5 commits before the HEAD
git diff HEAD~5
- Show changes from the last commit with 5 commits befor the HEAD for spacial files
git diff HEAD~5 file
-
Git log
-
Simple log
bashgit log
-
One line
bashgit log --oneline
-
Show graphicaly log
bashgit log --graph --oneline
-
Git stash
-
Save current changes to a specific (accessible) location and go to the last commit (tracted files)
bashgit add . git stash
-
Save current changes to stash (tracted & untracted files)
bashgit stash -u
-
Save current changes to stash (tracted & untracted & ignored [all] files)
bashgit stash -a
-
Show stash
bashgit stash show
-
Reverting stash changes (by stash number)
bashgit stash pop stash@{0}
-
Git Blame
Information about each line of a file
git blame file
-
Git Tag (readable name instead of hash name)
-
Create tag for this commit
bashgit tag "tag_name"
-
Assigning a tag to another commit based on hash name
bashgit tag "tag_name" 528a389
-
Git Reflog
git reflog
- Change last commit
git add file git commit --amend -m "new commit message"
-
Git Clean
-
Flags
i
: intractivef
: forced
: directoryn
: filex
: ignored files or directories
-
remove file in main path (untracted)
bashgit clean -n
-
remove directory in main path (untracted)
bashgit clean -d
-
Git Revert
git revert
is a Git command that reverses the changes of a specific commit by creating a new commit whithout deleting the history.
git revert <commit-hash>
- Git Reset
git reset
resets changes to a previous state ans can modify the commit history.
-
Type of
git reset
- soft(
--soft
): MovesHEAD
to a previous commit, keeping changes staged.
bashgit reset --soft <commit-hash>
- Mixed(
--mixed
) -> default: ResetsHEAD
and the staging area but keeps working directory changes.
bashgit reset --mixed <commit-hash>
- Hard(
--hard
): Deletes all changes from history, staging area, and working directory( irreversible!).
bashgit reset --hard <commit-hash>
- soft(
-
Git rm
git rm
removes files from the working directory and staging area. (Use git commit
to apply the changes permanently)
Usage
-
Remove a file and stage the deletition.
bashgit rm <file>
-
Remove from Git but keep it locally.
bashgit rm --cached <file>
-
Git Remote
-
SSH
- Generate ssh key
bashssh-keygen
Don't share
id_rsa
**You can just share
id_rsa.pub
- Add SSH in locally system
bashssh-add path/.ssh/id_rsa
- If you encounter an error while adding SSH, run blow command and follow description.
bashssh-agent -s
To fun : show keys of a persen added to github or gitlab with bellow trick
https://github.com/username.keys
DON'T SAVE Public keys from a person because you give him access to the system.
-
Show remote
bashgit remote
-
Set remote
bashgit remote add origin git@github.com:username/repo.git
-
Git Push
-
Push changes after seting up the remote when repository doesn't have this branch (Set up strem)
bashgit push -u origin new_branch
-
Git Checkout
-
Create Branch
bashgit checkout -b branch_name
-
Change branch
bashgit chekout branch
-
Git Rebase
-
An interactive way to modify commit history, allowing you to edit, reoeder, squash, or delet commits.
Command Short Command Description pick
p
Keep the commit unchanged in history(default). reword
r
Allows you to modify the commit messge. edit
e
Pauses the rebase process so you can modify the commit (1.g., edit files of add changes). squash
s
Merge this commit with the previous commit message unchanged. fixup
f
Similar to squash
, but it keeps the previous commit message unchanged.drop
d
Removes the commit from history. exec
x
Runs a shell command during the rebase process. bashgit rebase -i HEAD~n
-
Git Merge
-
Merge two branch (branch1 with main)
bashgit checkout main git merge branch1
-
Git Branch
-
Create branch
bashgit switch -C branch_name
OR
bashgit checkout -b branch_name
-
To check status of the commits
bashgit branch --verbose
-
Show list of branches
bashgit branch
-
Remeove branch
bashgit branch -d branch_name
-
Git Cherry Pick
-
cherry-pick
: Select specific commit from another branch and applies them to the current branch.bashgit cherry-pick <commit-hash>
Linux
- To show information of sytem
w
is the shortest linux command.
w
who
is similar tow
command but shorter.
-
Use
Ctrl + r
to search in the history of last commands. -
To find current path
pwd
- To mount external hard
sudo mount -t ntfs-3g /dev/sdb2 /mnt
- Exteract
example.zip
in to example/
unzip example.zip -d example
- find file
find [parent-path] -type [type] -iname "name"
find /home -type f -iname "file-*.txt"
-
cat & tac
-
cat
: show file from beginning to end.-n
-> number lines-b
-> number lines none block-A
-> end lines-s
-> remove white enter
-
tac
: show file from end to beginning. -
Change Python version
-
if call python run python2
bashsudo ln -sf /user/bin/python2 /user/bin/python
-
Changing user with root access
vim /etc/sudoers
user host=(user) command
-
go to line
#Allow root to run any commands anywhere
and added ...bashuser ALL=(ALL) ALL
-
The user can onlychange their password (passwd command)
bashuser ALL=(ALL) /bin/passwd
Ubuntu
- Move to monitors
Super + Shift + ⭠ ⭡ ⭣ ⭢
- Move window
Alt + F7 + ⭠ ⭡ ⭣ ⭢ + Enter
- Change size
Alt + F8 + ⭠ ⭡ ⭣ ⭢ + Enter
SSH
-
get IP config -> (int 127.23.21.11)
must be install
sudo apt install net-tools
bashifconfig
-
ssh to phone (android)
bashssh u0_aXXX@192.168.X.X -p 8022
SSH-KEYGEN
- generate ssh-kegen
ssh-keygen
- Introducing another system's IP and saving it in the current system
sudo vim /etc/hosts
append ip to hosts file
192.168.X.X other-sys
- easy ssh
ssh u0_aXXX@other-sys
SCP (secure copy)
- copy file
test.txt
from other sytem to this system (by recursive)
scp -r u0_aXXX@other-sys:test.txt .
User Management
Users
- Adding new user
sudo useradd <username>
- Set password to new user
sudo passwd <username>
- Go to new user
su - <username>
- Logout from user
exit
- Delete user
ps -u <username>
sudo kill -9 <PID> sudo pkill -u <username> sudo killall -u <username>
sudo userdel -r <username>
- User defaults
useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=no
LOG_INIT=yes
- Show and edit default useradd config
sudo vim /etc/default/useradd
- Show and edit default configs
sudo vim /etc/login.defs
Groups
- Show all groups
groups
- Add new groups
sudo groupadd <group_name>
- Changing the group of user
sudo usermod -G <new-group> <username>
- Append the user to the supplemental GROUS
sudo usermod -aG <new-group> <username>
- Removing group from user
sudo groupdel <group-name>
Login
- Show logins
loginctl
- Change Age (change time of stay in system)
chage <username>
Can change:
Minimum Password Age [0]:
Maximum Password Age [99999]:
Last Password Change (YYYY-MM-DD) [2025-04-30]:
Password Expiration Warning [7]:
Password Inactive [-1]:
Acount Expiration Date (YYYY-MM-DD) [-1]:
Password Manager
- Unlocking the password of an user
sudo passwd -uf <username>
- Locking the password af an user
sudo passwd -l <username>
- Changing the password with stdin
echo "password" | passwd --stdin <username>
Emmet (HTML-CSS)
HTML
-
Command:
a:www.google.com
- Description: Add
href
to the<a>
tag. -
Result:
html<a href="www.google.com"></a>
-
Command:
a[https://google.com]
- Description: Add
href
to the<a>
tag. -
Result:
html<a href="https://google.com"></a>
-
Command:
ul<li{example text $}*5
- Description: Add content to multiple
<li>
tags and repeat them. -
Result:
html<ul> <li>example text $</li> <li>example text $</li> <li>example text $</li> <li>example text $</li> <li>example text $</li> </ul>
-
Command:
ul>li#item$@-43*5
- Description: Inverse the number from 43, and create 5
<li>
elements with the inverted number as part of the content. -
Result:
html<ul> <li id="item-43">item-43</li> <li id="item-42">item-42</li> <li id="item-41">item-41</li> <li id="item-40">item-40</li> <li id="item-39">item-39</li> </ul>
-
Command:
table>(thead>tr>th{col$}*4) + (tbody>tr*3>td{row$-$}*4)
- Description: Create a table with automatic content, including a header and body rows with numbered columns and rows.
- Result:
html
<table> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> <th>col4</th> </tr> </thead> <tbody> <tr> <td>row1-1</td> <td>row1-2</td> <td>row1-3</td> <td>row1-4</td> </tr> <tr> <td>row2-1</td> <td>row2-2</td> <td>row2-3</td> <td>row2-4</td> </tr> <tr> <td>row3-1</td> <td>row3-2</td> <td>row3-3</td> <td>row3-4</td> </tr> </tbody> </table>
Text
- head
View the first 15 lines of the file
head -n 15 file.txt
- tail
View the last 15 lines of the file
tail -n 15 file.txt
- cat
Show files with line numbers
cat -n file.txt
-
grep
-
Filter file after line 190 by "ali"
bashgrep -A 190 ali file.txt
OR
bashtail -n 40 file.txt | grep ali
-
Filter file before line 190 by "ali"
bashgrep -B ali file.txt
-
To don't show phrase(for example: filter by ali but does include hadi)
bashgrep ali | grep -v hadi
-
To recursive filter
bashgrep -r .py ~/Desktop
-
egrep
For RegEx
-
find exactly a and 2 l
bashegrep 'al{2}' file.txt
-
find a and minimum 2 l
bashegrep 'al{2,}' file.txt
-
find a and maximum 2 l
bashegrep 'al{,2}' file.txt
-
diff
-
differente lines in 2 simailar files
bashdiff file1.txt file2.txt
-
cut
remove sections from each lines of files
-
Processing stdout
ls -lh
and get field 5 and 10 and saving into fileinfo.txtbashls -lh | cut --delimiter=" " -f 5,10 > fileinfo.txt
-
tr
translate or delete characters
-
lowercase to uppercase (freq -> FREQ)
bashecho 'freq' | tr [:lower:] [:upper:]
Phone
- get username
whoami
- get IP
pkg install net-tools
ifconfig
- run ssh in phone
sshd
- set password
passwd
AND
chmode 600 ~/.ssh/authorized_keys
- close ssh
exit
Z-shell
- git alias z-shell
grafical log
gloga
Bash
>
: write>>
: append<
: (stdin)
sort < file.txt
|
: pipe (stdin)
cat file.txt | sort
- (stdin)
sort file.txt
0
: stdin1
: stdout-
2
: stderr -
Bash completion
-
if bash completion is disable
bashsudo vim /etc/inputrc
chane
disable-completion on
todisable-completion off
or delete this line.bashset disable-completion off
-
variables
-
show variables
bashenv
-
show variables
bashecho $PWD
-
define temporary variable
bashexport MYVAR=/home/path
-
define permanently variable
vim ~/.bashrc
Adding variables permanently
# export SYSTEMD_PAGER= export MYVARFILE=/home/path
apply changes
source ~/.bashrc
- define alias
vim ~/.bashrc
adding alias command
# User specific aliases and function alias mydir="cd $MYVAR; ls -aF"
- bash history
show all commands
vim ~/.bash_history
run commands from history (for example run command 6)
!6
clear history
history -c history -w
- bash logout
write stdout of a command or function log whene logout bash (for example)
append stdout of ls -l
command into new_log
file
vim ~/.bash_logout
# ~/.bash_logout ls -l >> new_log
- bash profile
similar to bashrc
Bash Scripting
- shebang
#!/bin/bash
- bash scripting check writeable
ls -l
-
if not writeable
bashchmode +x bash_script.sh
-
run bash script
./bash_script.sh
-
comparison operator
-
eq
: equal gt
: greater thange
: greater equallt
: less thanle
: less equal
Comment line in bash scripting
- Single line
# line
- Multy line
: " line1 line2 line3 ... end line "
- Printf formatting
Specifier | Description |
---|---|
%% | Prints "%" symbol |
%c | Takes arguments as a single character |
%e & %E | Take argument in floating-point number and prints in exponential notation, %e for lower case letter and %E for capital letter |
%g & %G | Take argument in floating-point number and prints in normal or exponential notation |
%f | Takes argument as floting number |
%d | Takes arguments as signed integers |
%u | Takes arguments as unsigned integers |
%o | Takes argument as an unsigned octal number |
%x & %X | Takes arguments as unsigned hexadecimal integers |
Get Input
- Get input number and store on VAR
echo -n "enter number: " read VAR
- Get string input
echo "enter name: " read name
Condition
if [[ condition ]] then commands elif [[ condition ]] then commands else commands fi
For Loop
- Structure
for var in item1 item2 item3 do commands done
- For in the range
for num in {start..end..step} do commands done
Brake Loop
- Continue
for i in {1..5};do if [[ $i == 2 ]];then continue fi echo "Number: $i" done
- Break
for i in {1..5};do if [[ $i == 2 ]];then break fi echo "Number: $i" done
While Loop
- Structure
i=0 while [ Loop break condition ] do commands (( i++ )) done
- Infinite Loop
while : do commands loop_break_condition done
Read File
file=path/file while read -r line do echo $line done
Args
- Get Arguments
args=("$@") echo ${args[0]} ${args[1]}
- All Arguments
echo $@
- Number of Arguments
echo $#
Array
- Make Array
array=("item1" "item2" "item3" "item4")
- Geting the data from array
Use
@
to get all elementsUse
!
to get index of elementsUse
#
to get the number of elements
echo "${array[@]}" echo "${!array[@]}" echo "${#array[@]}"
Function
- Structure
function_name() { commands } function_name
- Return value
func_name() { echo "value" return 12 } func_name
output
value
Use $? to get numeric reterned vale
func_name() { echo "value" return 12 } func_name echo $?
output
value 12
- Get value from function
func_name() { local var="Linux" echo $var } variable="$(func_name)" echo "$variable"
- Send argumanet to function
func() { echo "hello, $1" } func "name"
- Use argv as function argument
func() { echo "hello, $1" } func $1
output
app_name.sh ali hello, ali
Database
Mongo DB
- Install MongoDB
- Start
sudo systemctl start mongod
- Enable
sudo systemctl enable mongod
- Run & Test
mongosh
- Exit
exit
- Show all database
show dbs
- Create or Connect Database
use my_database
- Create Collecation
db.createCollection("collection_name")
- Show Collections
show collections
- Current Database
db
- Remove Database
db.dropDatabase()
- Remove Collection
db.collection_name.drop()
- Add Data to collection
db.collection_name.insert({ name: 'ali', age: 23, salary: 5000 })
- Show all documents of a collection
db.collection_name.find({})
OR
db.collection_name.find({}).pretty()
- Show all documents in a collecation that contain condition
db.collection_name.find({name: "value"})
- Show one field in all document from collecation
db.collection_name.find({condition}, age:1, _id:0)
- Show document with limited results
db.collection_name.find({}).limit(4)
- Show documents and ignored numbers of first result
db.collection_name.find({}).skip(2)
-
Show documents with multi conditions
-
AND
mongodbdb.collection_name.find({age: 25, nmae: "ali"})
-
OR
mongodbdb.collection_name.find($or[{age: 30}, {name: "mahdi"}])
-
Greater Than or Less Than
$gt
-> greater than$lt
-> less than$gte
-> greater than equal$lte
-> less than equal$ne
-> not equal
mongodbdb.collection_name.find({age: {$gt: 15}})
-
Update document
db.collection_name.update({condition}, {$set:{age: 43}})
- Remove Objects contains similar values
db.collection_name.remove({column:value})
- Remove spacial objects
db.collection_name.remove({_id: ObjectId("shaID")})
Jupyter Notebook
- Write and create file by jupyter
%%writefile file.txt this is first line from content to write into the file this is second line for writing into file. ... this is last line to write into the file.
Python
- Precendence & Associativity of Arithmetic Operators
Periority | Operators | Associativity |
---|---|---|
1 | () | Left to Right |
2 | ** | Right to Left |
3 | +x and -x | Left to Right |
4 | *, /, //, and % | Left to Right |
5 | + and - | Left to Right |
-
Tips
- The output of division in Python is decimal number.
py30 / 2
>>> 15.0- Write large numbers in Python for convenience with underescores
py1_000_000_000 >>> 1000000000
-
Get and remove last value from list
lst = ["Ali", "Mohammad", "Mahdi"] name1 = lst.pop() print(name1) >>> Mahdi print(name1 is lst) >>> False print(lst) >>> ['Ali', 'Mohammad']
- Infinite Loop
while True: if 2 < 3: print("runing") break
OR
while 1: if 2 < 3: print("runing") break
Numpy
- Get All rows and columns from a matrix
import numpy as np arr = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) print(arr[...]) >>> array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Windows
-
Write text into a file by
CMD
HINT
: UseCtrl + z
to end writing and copying into the file.
copy con file.txt This is my text for copying to file. this is seconde line for copying to file. ... ... ... this is a last line to copeing into file. ^Z
- Read content a file in
CMD
copy file.txt con
output
This is my text for copying to file. this is seconde line for copying to file. ... ... ... this is a last line to copeing into file.
- Delet file by
CMD
del file.txt