Bash (Unix Shell)

Last modified 10 months ago / Edit on Github

Bash commands are mainly supported in MacOS, Linux but also support in Windows. You can use integrated tools for using bash on these platforms.

👉 Other "Shell" notes.

Tools

Hotkeys

  • Ctrl + C : interrupt current tasks.
  • Ctrl + L : clear the screen.
  • Tab : autocomplete the commands / directories / file names / ....
  • Ctrl + Shift + V : paste from clipboard.
  • For a long list: Enter to continue to read, q to quit.
  • Ctrl + A: move cursor to the beginning of the line.

Multiple commands

# run at once
command_1 && command_2

.sh file

Info icon

💡 #!/bin/bash tells your terminal to run the script with bash. There are also zsh, sh, fish,...

# using script: file.sh
#!/bin/sh
echo 'some info'
command_1
command_2

# and then sh file.sh
# with arguments
$file1 = $1
wc $file1 # word count

# multiple input args
for FILE1 in "$@"; do
wc $FILE1
done
NAME="defaut" # default value! DON'T HAVE SPACE!!!
# with flags
while getopts n:f: option; do
case "${option}"
in
n) NAME=${OPTARG};;
f) FILE=${OPTARG};;
esac
done

echo $NAME
wc $FILE

# how to use?
sh test.sh -n "ThiD" -f test.md

Search / grep / sed

# all files / folders containing 'abc'
ls | grep -i abc
# find command lines containing 'abc'
dpkg -l | grep -i abc
# search and extract a part of result
pip show numpy
# Location: /usr/lib/python3/dist-packages
pip show numpy | sed -n 's/Location: //p'
# /usr/lib/python3/dist-packages

Check info

System

# Change password
passwd
# DISK SPACE
df -h
# like monitor
top
# MEM USAGE
free -m
# ALL ENV
printenv

# add new
export ABC=/xyz/thi/
# NVIDIA
nvidia-smi
lspci -nn | grep '\[03' # another way
# list of devices
lsusb
# list display screen
xrandr --listactivemonitors
# CPU
cat /proc/cpuinfo | grep 'model name' | uniq # model
cat /proc/cpuinfo | grep 'vendor' | uniq # vendor
cat /proc/cpuinfo | grep processor | wc -l # number of processes

Folders / Files

# CHANGE ACTIVE DIR
cd <dir>
cd # to the startup dir
cd / # to root
cd .. # to father dir
cd - # back to previous dir
# CREATE NEW FOLDER
mkdir <dir>
# LIST
ls
ls -a # including hidden
ls | grep 'ubuntu' # files containing 'ubuntu' in name
# CURRENT PATH
pwd # or echo ${pwd}

# PARENT OF CURRENT PATH
echo $(dirname `pwd`)
# FOLDER/FILE SIZE
du -hs <directory / file>
# `h` : human readable (6.7G)
# `s` : display size

# all folders/files of current folder
du -hs * | sort -rh

# only folders
du -sh ./*/

# only first 5 retrieves
du -h /home/thi/ | sort -rh | head -5
# REMOVING
rm <file>
rm -f <file> # force to remove
rm -rf <dir> # remove folder
rmdir <empty-dir> # remove empty
# COMPRESS
zip file.zip file/folder
unzip file.zip # decompress
# PRINT TREE folder structure
tree
tree -d # only folders
tree -d -I 'abc' # except folder "abc"
tree -I 'abc|xyz' # except folder "abc" and "xyz"
tree -I 'test_*|__pycache__|__init__.py' # use wildcat
tree -L 2 # level 2
tree -P 'test_' # list only files starting with "test_"

Permission

👉 Chmod code calculator.

# list of groups
groups
# which groups a user belongs to
group <user_name>
id -nG # or
# check info of a current user
id <user_name>
# list all members of a group
grep <group_name> /etc/group
# CHECK PERMISSION
ls -l
ls -l <file>
# ADD existing USER to existing GROUP
sudo usermod -a -G groupName userName
# CHANGE PERMISSION
chown <user>:<group> file
chown -R thi:root folder # folder & children

Network

# CHECK IP
ifconfig
ipconfig # windows
# DOWNLOAD A FILE
wget https://website.com/filename.ext
# open ports
sudo apt install nmap
nmap localhost
# very simple server
python3 -m http.server # localhost:8000
python3 -m http.server 1337 # localhost:1337
# current running servers
sudo apt install net-tools
netstat -lepunt

# kill a process, e.g. 29231/ssh
kill <pid> # eg. kill 29231
# Kill a port
kill $(lsof -t -i:4000)
# mb data used
sudo apt install vnstat
vnstat -d
# INTERNET SPEED (need python)
curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python -
# (1st test on mac)
# Look for which ports are running
# Find their PID
# Kill them
brew install nmap
nmap localhost
lsof -i:8080
kill <PID>

# in case above command cannot solve the problem
sudo lsof -i -P | grep "8080"

Text file

# QUICK LOOK CONTENT
more file.txt
cat file.txt
# JUST CREATE
touch file.txt
# CREATE + MODIFY
nano file.txt # Ctrl+X to quit
vim file.txt # ESC, :q to quit
# SEARCH STRING
grep "string" file.txt
# ADD A LINE TO A FILE WITHOUT OPENNING IT
echo "hello 'thi' world" >> my_file.txt

Images

# open an image
eog image_file.jpg
# Create
ln -s original_folder sym_folder

# Remove
rm sym_folder

Alias

Create your own "alias" command for short,

# CREATE
alias yourAlias='cd /usr/'
alias yourAlias=cd /usr/ # windows
# CALL
yourAlias
# LIST OF ALIASES
alias
alias abc # "abs" stands for what?
# remove an alias
unalias abc
# group of commands
my_alias() {
screen -S dat -dm bash -c "cd /dinhanhthi.com; iserve; exec sh"
}
# list of commands
my_alias(){
cd /home/user/git/abc/
git add .
git commit -m "abc"
git push
}
# With parameter
alias testing="echo $1"
# Run as `testing abc`

my_alias() {
cd thi/
echo $1
}
# Used as `check_samples "api"` or just `check_samples`
check_samples() {
if [ ! -z $1 ]; then # If there is parameter
python scripts/check_samples.py | grep $1
else # If there is no parameter
python scripts/check_samples.py
fi
}
More options
  • Linux / MacOS: Add your alias to .bash_aliases (in home dir, printenv HOME) if you wanna store your alias permanently.
  • Windows: Using cmder (its setting file), add more aliases to <cmder-install>/config/user_aliases.cmd. You can also add (automatically) on the cmder UI, it adds them for you to the .cmd file.

Create / Copy / Cut / Paste

# Create a new folder
mkdir <folder>
mkdir -p <folder> # already exist accepted
# MOVE
mv <old-dir> <new-dir>
move <old-dir> <new-dir> # windows
# RENAME a file/folder
mv olname.txt newname.txt
# COPY
cp file file
cp -r file&dir file&dir

Display

# only display 3 last directory names
PROMPT_DIRTRIM=3
# display only user:current_folder#
PS1='\u:\W\$ '

References

💬 Comments

Support Thi Support Thi