Bash
Frequently used bash snippets
Check memory from bash
free -mh
Check access through ssh
last | head
Check open ports nmap
while :;
do nmap <addres> -p443,9200,80,22 -Pn --max-rtt-timeout 60ms ;
sleep 1 ; done
Check open ports lsof
sudo lsof -i -P -n #or
sudo lsof -i -P -n | grep LISTEN #or
lsof -i :8000 # by port
Openning port in ubuntu
sudo ufw allow [PORT]
If statements
if [ -z STRING]
then
fi
If with multiple conditions and checking lenght == 0
if [ -z $VAR1 ] || [ -z $VAR2]; then
# code
fi
Uninstall packages
sudo apt remove pkg
Kill processes
kill -9 PID
Search keywords in files within a directory
grep -Hrn 'search term' path/to/files
Remove character in-place
sed -i 's/past/future/g' file.txt
Remove a specific line from file
sed -i 'Ld' file.txt
# L is the linenumber to delete
Add character to the beginning of the file
sed -i '1s/^/future/' file.txt
Remove first line from file
tail -n +2 FILE
Create sudo user
adduser username
usermod -aG sudo username
List omitting directory
ls -1R -I [omit_dir]
Collect http urls from several csv into a single one
cat urls.html | grep -Eo "(http|https)://[a-zA-Z0-9./?=_%:-]*" | sort -u
cURL requests
curl --header "Content-Type: application/json" \
--request POST \
--data '{"username":"xyz","password":"xyz"}' \
http://localhost:3000/api/login
Delete history entry
history -d <line_number>
tmux
Create a new session
tmux new -s sessionName
## Detached mode:
#tmux new -d -s sessionName
List sessions
tmux ls
Attach a session
tmux a -t sessionName
Detach a session
C-a + d
Send a command to a detached session
tmux send-keys -t sessionName.0 "echo 'Hello world'" ENTER
Split panes for detached sessions
tmux splitw -h -p 50 -t sessionName:1.0
# -p percentage of the display for the created pane
# -h or -v # horizontal/vertical splitting
## if we need to do it again we may need to select the pane we want to split first
tmux select-pane -t sessionName:1.0
tmux splitw -h -p 50 -t sessionName:1.0
Compress file
tar -zcvf outputFileName folderToCompress
unzip file
sudo apt install unzip #(ubuntu)
unzip target_file.zip
Text processing
Get specific line from file
sed -n LINEp target_file
awk > sed for big files
Substitute char in big file
aws '{gsub(/old/,"NEW"); print}' in_file > out_file
Might require LC_ALL=C at the beginning depending on in_file encoding
Get content between START and END pattern
sed -n '/^CREATE TABLE/,/GO/p'
Generate a password or key
openssl rand -base64 32
Generate base64 encoded for text
echo 'to_encode' | base64
References
Last updated
Was this helpful?