Linux
- Linux
- Books and articles
- Ubuntu
- Tools
- Bash shell programming
- ZSH
- SMB drive mappings
- Ubuntu key shortcuts
- Installing Packages
- Checking network usage
- User Stuff
- SSH tips
- Bash profile \& History
- Cleaning Snaps
- FStab
- Managing Swap space
- Managing /var space
- Setting java version
- Cron
- Using Screen
- TMux
- Filesystem overview
- Small Linux installs
- SED AWK
- Annoying repeated - "System program problem detected" messages
- CURL
- Terminal Commands
- Moving and copying files
- Checking number of CPUs - lscpu
- SCP \& cp
- Rsync
- Linux IP address
- Monitoring processes - top, vmstat, sysstat
- top cheatsheet
- tar
- tcpdump
- mkdir creating directories
- ifconfig is dead, use ip instead
- Disk Usage, Disk Free space
- Xargs
- netstat
- Lookup hostname from IP address
- File Permissions
- Find utility
- List files in directories in a Tree
- Symbolic links
- Word Counts - find number of files in dir
- Grep
- Grep to find text within files
- Working with yaml and json
- System Suspend from commandline
- Ubuntu on a netbook
- Docker Installs for Linux - Ubuntu
- Mini Cheatsheet
- Learning Docker
- Docker Compose
- XHCI issues
- Screenshots
- List of Linux Topics
- Vim Cheatsheet
- Less Cheatsheet
Books and articles
- https://linuxcommand.org/index.php and the pdf version https://netcologne.dl.sourceforge.net/project/linuxcommand/TLCL/19.01/TLCL-19.01.pdf
- Gamifying linux learning - https://www.reddit.com/r/linux4noobs/comments/luzgz9/looking_for_websites_like_overthewire_to_learn/
Ubuntu
- https://itsfoss.com/things-to-do-after-installing-ubuntu-18-04/
- How to make an OS with linux and Raspberry PI - https://s-matyukevich.github.io/raspberry-pi-os/
Ubuntu Midi keyboard
- Super Basic HowTo Connect a MIDI Keyboard - https://ubuntuforums.org/showthread.php?t=1303306
Recording screen + audio
- Simple Screen Recorder - https://itsfoss.com/record-screen-ubuntu-simplescreenrecorder/
- One I used in work which seems to work well (even though people mention not supporting Wayland)
- Discussion on LinuxMint - https://forums.linuxmint.com/viewtopic.php?t=350180
- OBS tool https://obsproject.com/download
Tools
Video editor
- List of video editors - https://itsfoss.com/best-video-editing-software-linux/
- I took Open Shot
Pavucontrol for audio
- https://stackoverflow.com/a/66009679/864024
- pavucontrol
allows you to have a list of the sources for input output audio and select per running application
Onedrive sync for linux
- https://www.maketecheasier.com/sync-onedrive-linux/
- https://www.linuxuprising.com/2020/02/how-to-keep-onedrive-in-sync-with.html
- Simple with RClone - https://www.linuxuprising.com/2018/07/how-to-mount-onedrive-in-linux-using.html
My Notes:
- Reading the pages above I went to the onedrive client github and followed the install instructions
sudo apt install build-essential
sudo apt install libcurl4-openssl-dev
sudo apt install libsqlite3-dev
sudo apt install pkg-config
sudo apt install git
sudo apt install curl
curl -fsS https://dlang.org/install.sh | bash -s dmd
# For notifications
sudo apt install libnotify-dev
- Following the dependency installs I followed the compile section
- Activate dmd following the output of the install from above
Run `source ~/dlang/dmd-2.098.1/activate` in your shell to use dmd-2.098.1.
This will setup PATH, LIBRARY_PATH, LD_LIBRARY_PATH, DMD, DC, and PS1.
Run `deactivate` later on to restore your environment.
- After that the make etc. worked and I could authorize the app with onedrive
- onedrive –synchronize –single-directory ‘LinuxSync'
Taskwarrior - a todo list on the commandline
- Detailed online documentation https://taskwarrior.org/docs/
# Cheatsheet
# basic functions
$ task list
$ task add Some description
$ task 1 done
$ task 1 delete
# Add priority
$ task add priority:H Pay bills
# Show tasks ordered by priority
$ task next
# With a project
task add project:Home Some description
Sqlite on command line
Some links
- Basic tutorial to see syntax: https://www.sqlitetutorial.net/
- Selects https://www.sqlitetutorial.net/sqlite-select/
# Connect to a DB file
$ sqlite3 mySQLLiteFile.db
# Once connected, you have the sqllite command prompt
sqlite>
# Exit from sqlite command prompt :)
Ctrl+d
# Command to list all tables
.tables
# Comamnd to select something from a table - NB for ; at the end
select * from MyTable where someColumnName = '%partialValueMatch%';
Presentation tools
Slidev
- https://sli.dev/
- I used the docker image to avoid installs - https://sli.dev/guide/install.html#install-on-docker
- Some small drawbacks
- must use slides.md as the file name and have one per folder
- Some small drawbacks
- I used the docker image to avoid installs - https://sli.dev/guide/install.html#install-on-docker
# run the docker image
docker run --name slidev --rm -it --user node -v ${PWD}:/slidev -p 3030:3030 tangramor/slidev:latest
# Export the slides to static SPA - NB need to update the relative links "/assets" becomes "./assets". Also need to run on a webserver
docker exec -i slidev npx slidev export
Reveal MD
Bash shell programming
- dedicated page:
- TODO - proper link to dedicated scripting page
- Links to some nice resources for Shell and command-line - https://www.reddit.com/r/linuxquestions/comments/ewbl9f/explainshellcom_is_an_awesome_resource/
- Really NICE SITE TO BREAKDOWN COMMANDS AND EXPLAIN THEM: https://explainshell.com/
- PDF with a LOT of different resources - https://www.usenix.org/sites/default/files/conference/protected-files/lisa19_maheshwari.pdf
ZSH
- https://medium.com/@harrison.miller13_28580/bash-vs-z-shell-a-tale-of-two-command-line-shells-c65bb66e4658
- https://www.howtogeek.com/362409/what-is-zsh-and-why-should-you-use-it-instead-of-bash/
- Nice getting started guide - https://www.sitepoint.com/zsh-tips-tricks/
- https://github.com/derailed/k9s
- https://webinstall.dev/
- https://github.com/romkatv/powerlevel10k#oh-my-zsh
- https://github.com/ohmyzsh/ohmyzsh
- Also install some extra fonts - https://github.com/powerline/fonts
- Productivity plugins - https://travis.media/top-10-oh-my-zsh-plugins-for-productive-developers/#20210719-json
powerline10k
- following guide in readme - https://github.com/romkatv/powerlevel10k#meslo-nerd-font-patched-for-powerlevel10k
# from mint machine
dog@kennel:~$ zsh
New config: ~/.p10k.zsh.
Backup of ~/.zshrc: /tmp/.zshrc.JZtb3qunUJ.
See ~/.zshrc changes:
diff /tmp/.zshrc.JZtb3qunUJ ~/.zshrc
SMB drive mappings
This is where an SMB share is mapped when you've added it in Nautilus/Filemanager: /$XDG_RUNTIME_DIR/gvfs
Ubuntu key shortcuts
à - AltGr ` a
è - AltGr ` e
é - AltGr ' e
€ - AltGr = e
ç - AltGr , c
ê - AltGr Shift+> e
Installing Packages
Apt and apt-get
Apt command was added by linux in 2014 to combine commonly used features of apt-get and apt-cache
- apt-get: installing, upgrading and removing software packages.
- apt-cache: search for new packages.
Can possibly need to execute with sudo
# installing/removing a particular package
sudo apt install nmap
sudo apt remove nmap
sudo apt purge nmap
# Updating package lists and then upgrading them. Can also upgrade individual packages by name
sudo apt update
sudo apt upgrade
# List all packages, grep for a particular package. Version is also displayed.
$ apt list
$ apt list | grep <packageName>
$ apt list --installed
$ apt list --upgradeable
# Search for package in available packages, show information about a package - dependencies, installation size, package source
$ apt search package_name
$ apt show package_name
- Apt tutorial page - https://phoenixnap.com/kb/how-to-use-apt-get-commands,
- Another one - https://linuxize.com/post/how-to-use-apt-command/
Using Debian package manager
# seeing a list of installed packages
dpkg -l | less
dpkg -l <packageName>
#To check whether a package is installed or not:
dpkg -l {package_name}
dpkg -l vlc
dpkg -l | grep vlc
Show the location where the package is installed. The "-S" (capital S) stands for "search"
sudo dpkg -S {package_name}
sudo dpkg -S skype
# Installing a local package
sudo dpkg -i package_file.deb
Checking Kernel and system info
uname -a # for all information regarding the kernel version
uname -r # for the exact kernel version
lsb_release -a # for all information related to the Ubuntu version,
lsb_release -r # for the exact version
sudo fdisk -l # for partition information with all details.
dpkg -l | grep linux-image # displays all installed kernels
dpkg -l | tail -n +6 | grep -E 'linux-image-[0-9]+'
apt-mark showmanual 'linux-image-.*' # show manually installed kernels
apt-mark showauto 'linux-image-.*' # show auto installed kernels
sudo apt --purge autoremove # remove unused old kernels (only removes auto installed kernels I think)
- Information on cleaning up old kernels - https://help.ubuntu.com/community/RemoveOldKernels
- Updating kernel via grub reboot
- sudo grub-reboot "Advanced options for Ubuntu>Ubuntu, with Linux 4.2.0-16-generic"
- sudo reboot
Checking version of linux
# Get the initial flavour
cat /proc/version
# Then followup with specific commands
# Red Hat for example
cat /etc/redhat-release
# Debian
cat /etc/debian_version
# or in general :
cat /etc/*-release
# Also you could use the following command
cat /etc/issue
Checking Hardware Configuration
lshw command for checking configuration
lshw is a small tool to extract detailed information on the hardware configuration of the machine.
It can report exact memory configuration, firmware version, mainboard configuration, CPU version and speed,
cache configuration, bus speed, etc. on DMI-capable x86 or IA-64 systems and on some PowerPC machines (PowerMac G4 is known to work).
- Checking RAM Slots
sudo lshw -class memory
# Results look like this for 2 RAM slots (Banks) which are both used:
*-memory
description: System Memory
physical id: 4d
slot: System board or motherboard
size: 16GiB
*-bank:0
description: SODIMM DDR4 Synchronous Unbuffered (Unregistered) 2400 MHz (0.4 ns)
product: HMA81GS6AFR8N-UH
vendor: Hynix Semiconductor (Hyundai Electronics)
physical id: 0
serial: 2C9D672E
slot: DIMM A
size: 8GiB
width: 64 bits
clock: 2400MHz (0.4ns)
*-bank:1
description: SODIMM DDR4 Synchronous Unbuffered (Unregistered) 2400 MHz (0.4 ns)
product: HMA81GS6AFR8N-UH
vendor: Hynix Semiconductor (Hyundai Electronics)
physical id: 1
serial: 2C9D6723
slot: DIMM B
size: 8GiB
width: 64 bits
clock: 2400MHz (0.4ns)
- Sensors - checking cpu temp etc.
Checking network usage
# See what process send/receives most packets
netstat -anp --inet
Checking active network interface and traffic
# Interface is connected if link=yes
$ sudo lshw -c network | egrep 'description|name|link'
#Monitor the traffic on connected interfaces:
$ watch ip -s link
User Stuff
- Checking user groups - https://www.cyberciti.biz/faq/which-groups-do-i-belong-to/
$ groups
$ whoami
SSH tips
- Using ssh-add to keep ssh passphrase in session - https://kb.iu.edu/d/aeww
- ssh academy - ssh, keygen etc. - https://www.ssh.com/academy/ssh
- ssh Copy-ID to add ssh keys to authorized keys - https://www.ssh.com/academy/ssh/copy-id#how-ssh-copy-id-works
links about using ssh agent & security
- https://www.commandprompt.com/blog/security_considerations_while_using_ssh-agent/
- https://stackoverflow.com/questions/18880024/start-ssh-agent-on-login/
- https://linux.101hacks.com/unix/ssh-agent/
- https://stackoverflow.com/questions/2205282/ssh-agent-and-crontab-is-there-a-good-way-to-get-these-to-meet/
- https://stackoverflow.com/questions/24495395/using-cron-with-ssh-keys/
- This one looks promising for a fully programatic way to do it by handling the ssh agent stuff on and off - https://www.akadia.com/services/ssh_agent.html
- https://stackoverflow.com/questions/869589/ why-ssh-fails-from-crontab-but-succedes-when-executed-from-a-command-line
Some other articles about ssh login without password (NB - ssh agent solution is useful)
- https://stackoverflow.com/questions/1595848/configuring-git-over-ssh-to-login-once
- talks about keychain and -K option for restarts - https://stackoverflow.com/questions/21095054/ssh-key-still-asking-for-password-and-passphrase
- https://stackoverflow.com/questions/18880024/start-ssh-agent-on-login
- https://stackoverflow.com/questions/12033249/ssh-agent-forwarding-inside-cron-jobs
Bash profile & History
- https://www.shellhacks.com/tune-command-line-history-bash/
- Tune the number of lines kept, when it gets written (end of session or immediately)
- https://www.cherryservers.com/blog/a-complete-guide-to-linux-bash-history
- history command lists the history with a line number
- history -d
or to delete
- Adding a space before a command will not add it to history (not in all distros)
Cleaning Snaps
- https://superuser.com/questions/1310825/how-to-remove-old-version-of-installed-snaps
- Also here some tips for managing the snaps: https://www.linuxuprising.com/2019/04/how-to-remove-old-snap-versions-to-free.html
FStab
The configuration file /etc/fstab contains the necessary information to automate the process of mounting partitions.
- Mounting fstab without reboot - https://www.shellhacks.com/remount-etc-fstab-without-reboot-linux/
Managing Swap space
- swap file instead of partition - https://linuxize.com/post/create-a-linux-swap-file/
- Also here with some info about using dd not fallocate - https://www.howtogeek.com/455981/how-to-create-a-swap-file-on-linux/
- And from the Ubuntu docs - https://help.ubuntu.com/community/SwapFaq#How_much_swap_do_I_need.3F
# Commands to use - NB I have more space on /home than elsewhere but can put anywhere
# Use ONE of the following to create the swap file - I used second way
sudo fallocate -l 10G /home/swapfile # this is the quick and easy way
sudo dd if=/dev/zero of=/home/swapfile bs=1024 count=10485760 # this is more portable
# setup the swap file for use (permissions to root for using it)
sudo mkswap /home/swapfile
sudo chmod 600 /home/swapfile
sudo swapon /home/swapfile
# Add to fstab to make the change permanent
sudo vim /etc/fstab
#Add this line
/home/swapfile swap swap defaults 0 0
Managing /var space
- Clean way is to correctly organise at install :) but otherwise can resize the logical volume
- For docker you can use a configuration to point to another storage location (todo - exapand on this point)
- Other way which is much simpler is to create a softlink to a directory on another volume
sudo systemctl stop snapd.service
sudo mv /var/lib/snapd /home/snapd
sudo ln -s /home/snapd /var/lib/snapd
sudo systemctl start snapd.service
NB THIS DOESN'T work for SNAPS :(
- Some suggestions here: https://askubuntu.com/questions/1029562/move-snap-packages-to-another-location-directory
- This I have used and it works very well.
- https://forum.snapcraft.io/t/where-is-a-snap-stored-and-how-can-i-change-that/3194/4
script from the above askubuntu solution for mount –point
##############################################################################
# Take Care this section may break the System !!!
##############################################################################
##Move snap folder to Home instead of root.
#Create the directory : you can change the location
mkdir /home/$USER/snap/snapd
#Copy the data
sudo rsync -avzP /var/lib/snapd/ /home/$USER/snap/snapd/
#Do backups
sudo mv /var/lib/snapd /var/lib/snapd.bak
sudo cp /etc/fstab /etc/fstab.bak
#Change fstab (Change $USER with your name or change the path totally)
echo "/home/$USER/snap/snapd /var/lib/snapd none bind 0 0" | sudo tee -a /etc/fstab
#remount fstab Or reboot.
sudo mkdir /var/lib/snapd
sudo mount -a
if ls /var/lib/snapd/ | grep snaps
then
echo "Re-mounting snapd folder is done successfully. !!!!"
sudo rm -rf /var/lib/snapd.bak
else
echo "WARNING : Re-mounting snapd folder failed, please revert !!!!! "
echo "WARNING : Re-mounting snapd folder failed, please revert !!!!! "
echo "WARNING : Re-mounting snapd folder failed, please revert !!!!! "
echo "WARNING : Re-mounting snapd folder failed, please revert !!!!! "
echo "WARNING : Re-mounting snapd folder failed, please revert !!!!! "
# Trying to revert automatically
sudo cp /etc/fstab.bak /etc/fstab
Setting java version
sudo update-alternatives --display java
sudo update-alternatives --config java
I followed this tuto for installing java + setting the JAVA_HOME https://www.digitalocean.com/community/tutorials/how-to-install-java-with-apt-on-ubuntu-18-04
it set JAVA_HOME in /etc/environment which updates for ALL users of the system which isn't necessarily the right way :).
# Searching for JAVA_HOME setting
$ grep JAVA_HOME ~/.bashrc_custom ~/.bash_login ~/.profile ~/.bashrc
$ grep JAVA_HOME /etc/environment /etc/bash.bashrc /etc/profile.d/* /etc/profile
...Found it in /etc/environment
Using SDKMan for java installs on Linux
- Article about setup - https://mydeveloperplanet.com/2022/04/05/how-to-manage-your-jdks-with-sdkman/
- Main SDKMan site - https://sdkman.io/
Cron
- Site to help setup crontab entries - https://crontab.guru/
- Overview - https://phoenixnap.com/kb/set-up-cron-job-linux
Simple Commands
# List crons
crontab -l
# edit crontab for current user
crontab -e
Using Screen
- https://linuxize.com/post/how-to-use-linux-screen/
- User Manual https://www.gnu.org/software/screen/manual/screen.html
# Useful commands
- On the command prompt, type screen.
- Run the desired program.
- Use the key sequence Ctrl-a + Ctrl-d to detach from the screen
session.
- Reattach to the screen session by typing screen -r.
# Create new window 0-9
- Ctrl+a c Create a new window (with shell)
- Ctrl+a " List all window
- Ctrl+a 0 Switch to window 0 (by number )
- Ctrl+a A Rename the current window
# Navigating
- Ctrl+a n switch to next window
- Ctrl+a p switch to previous window
- Ctrl+a S Split current region horizontally into two regions
- Ctrl+a | Split current region vertically into two regions
- Ctrl+a tab Switch the input focus to the next region
- Ctrl+a Ctrl+a Toggle between the current and previous region
- Ctrl+a Q Close all regions but the current one
- Ctrl+a X Close the current region
# detach and reattach
- Ctrl+a d - detach from Linux Screen Session
- screen -r - resume screen session
- screen -r 10835 - resume for screen session 10835 (see screen -ls
below)
# list all screens running on the machine
- screen -ls
Alternative to screen for an already running process
# How-to:
# Ctrl+z to interrupt,
bg #to put in background,
jobs # to see job number,
disown %<jobNumber> # get the <jobNumber> value from jobs command
TMux
Alternative to Screen and maybe more user friendly
Example Tmux commands
# Start a session with a name
$ tmux new -s <session_name>
# For TMux start giving a command by Ctrl+b then the command, similar to Ctrl+A for Screen
# Create a new window/tab
$ c
# List windows/tabs
$ w
# Navigate windows - Next, Previous, numbered window
$ N
$ P
$ 0-9
# Split window
$ % # vertical split
$ \" # horizontal split
$ up,down,left,right # navigate splits
# Attach/Detach from sessions
$ D # detaches from session but leaves it running in the background
$ tmux attach-session -t <session_name> # e.g. geek-1
# List running sessions
$ S
Filesystem overview
Small Linux installs
Some small Linux installs for old computers - less than 1GB ram needed.
- Puppy Linux - create a Live CD, then can install on USB stick and use on any computer
- Zenix - everything fits on USB live stick
Install utilities - USB boot keys etc
UNetBootIn - Utility for creating USB live sticks for Linux distros
The Mac version has an annoying bug where you need to do an fdisk on the usb stick after formatting but before creating your install in order to activate the partition.
Creating a boot USB key
- Using dd to flash an iso to a USB key - https://medium.com/@tbeach/use-unix-dd-command-to-os-bootable-on-usb-drive-6671945d95a6
Ventoy - bootable usb drives
- https://www.ventoy.net/en/index.html
- Not sure if I've ever used this utility
Beautiful icon sets
SED AWK
SED Stuff
- SED documentation - http://www.tldp.org/LDP/Bash-Beginners-Guide/html/chap_05.html
- Better SED examples -
Simple SED examples
# Delete everything between BEGIN and END lines for all *.txt files, creating a backup .bak for each one and modifying the original
sed -i.bak '/BEGIN/,/END/d' *.txt
# same thing with another string
sed -i.bak2 '/EditStuff/,/EditStuffFinish/d' *.err
SED - Adding stuff to the end of the line
# Finds end of line with $, then adds ":80" to it
sed -n 's/$/:80/' ips.txt > new-ips.txt
Miscellaneous SED stuff
- Special Chars - https://stackoverflow.com/questions/43108359/how-to-remove-all-special-characters-in-linux-text
- Print previous line before match - https://unix.stackexchange.com/questions/206886/print-previous-line-after-a-pattern-match-using-sed
- Windows carriage return ^M in files - https://superuser.com/questions/194668/grep-to-find-files-that-contain-m-windows-carriage-return
AWK Stuff
- AWK documentation - http://www.tldp.org/LDP/Bash-Beginners-Guide/html/chap_06.html
Annoying repeated - "System program problem detected" messages
System program problem detected gets displayed repeatedly after there has been a crash. Mostly its okay to delete the reports
# See the list of crash reports ll /var/crash/
total 988 drwxrwsrwt 2 root whoopsie 4096 Jan 17 15:55 ./ drwxr-xr-x 15
root root 4096 Jul 25 2018 ../ -rw-r\--r\-- 1 kernoops whoopsie 2648 Jan
15 11:30 linux-image-4.18.1-041801-generic.220862.crash -rw-r\-\-\-\-- 1
root whoopsie 28316 Jan 17 10:57
\_usr_bin_landscape-package-changer.0.crash -rw-r\-\-\-\-- 1 dcostello
whoopsie 967043 Jan 17 15:55 \_usr_bin_onedrive.1000.crash
# Remove if it's okay
sudo rm /var/crash/*
CURL
- Nice overview of options - https://gist.github.com/subfuzion/08c5d85437d5d4f00e58
- Tips on displaying just headers - https://catonmat.net/cookbooks/curl/print-response-headers
-s -o /dev/null -D -
- Use the above to get ONLY headers printed :) complex indeed !!!
Example of CURL Post
curl -s -o /dev/null -D - --location --request POST 'https://somesite.com' \
--data '@somefile.json'
# useful options
-i, --include # include HTTP Headers in the output
Terminal Commands
Moving and copying files
# Move multiple files/directories to a directory
mv -t <DESTINATION> <source1> <source2> ......
Checking number of CPUs - lscpu
$ lscpu
# example output
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 2
Core(s) per socket: 4
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 142
Model name: Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz
Stepping: 10
CPU MHz: 3595.397
CPU max MHz: 4200.0000
CPU min MHz: 400.0000
BogoMIPS: 4224.00
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 8192K
NUMA node0 CPU(s): 0-7
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp flush_l1d
SCP & cp
- SCP examples - https://haydenjames.io/linux-securely-copy-files-using-scp/
# Simple example of copy to remote
scp somefile.txt myuser@myhost:~/somedirectory
# Recursive copy
cp -r <pathToTarget> <pathToDest>
# Copy multiple named files
cp ./{File1,File2,File3} <pathToDest>
Rsync
-
Use to sync local or remote directories - https://www.digitalocean.com/community/tutorials/how-to-use-rsync-to-sync-local-and-remote-directories
-
Options
- -a - most commonly used "archive" which preserves all timestamps, permissions etc. and works recursively
- -r - just recursively
# Remote rsync
rsync -a ~/dir1 username@remote_host:destination_directory
Linux IP address
ifconfig when root (or $cd /sbin/ then $./ifconfig if not) or $curl whatismyip.org
Monitoring processes - top, vmstat, sysstat
- Sysstat - suite of tools to monitor https://github.com/sysstat/sysstat
- top command
- vmstat - http://man7.org/linux/man-pages/man8/vmstat.8.html
# TOP - log out to a file in batch mode -n iterations -d interval in secs -o order by field -b batch mode
top -n 10 -d 2 -o %CPU -b \> \~/dcTOP.txt
# To limit output can run top once interactively, limit number of
processes with n then W to write a user config file
# VMSTAT - gives memory and cpu info - the command below will run it with a timestamp, format the memory in MB and repeat every 30s for 500 repetitions (enough for 2hrs of info)
vmstat -t -S M 30 500 2>&1 | tee vmstats.txt
top cheatsheet
- After running top command:
- Shift+m - Sort processes by memory usage
- c to toggle between full command line and process name
- Shift+f to enter the interactive menu
- press the up or down arrow until the %MEM choice is highlighted
- press s to select %MEM choice
- press enter to save your selection
- press q to exit the interactive menu
- Specify the sort order on the command line
- top -o %MEM
tar
# Tar and zip
$ tar zcpfv dokuwiki-backup.tar.gz /path/to/dokuwiki
# unzip
$ tar zxvf dokuwiki-xxxx-xx-xx.tgz
# Example of finding and then tar-ing files
$ find Interfaces/ -name "*DC003*" -mmin -20 -print0 | tar -czvf ~/QF_FBA_Weight/backup.tar.gz --null -T -
# Example of un-taring and creating a target directory for the -C option ($_ is a special bash variable to get the output of the previous command)
$ mkdir -p /target/dir && tar -C $_
Julia Evans cartoon of it: https://twitter.com/b0rk/status/993682480069824512?lang=en
{width="800"}
Extract files to directory named from zip file
tar -xzf someArchive.tar.gz --one-top-level
tcpdump
- Intro to tcp dump - https://opensource.com/article/18/10/introduction-tcpdump
- Gives basic setup and usages
- Julia Evan's EXCELLENT comic https://jvns.ca/tcpdump-zine.pdf
Docker page also for docker specific usage of tcp dump - "Related Articles for TCPDUMP"
$ sudo tcpdump -v -i any -c250 -nn host 10.56.208.4
# read verbose on any network interface, 250 messages, filter by host
mkdir creating directories
# Create a dir, if the parent directories don't exist, create them too
$ mkdir -p /target/dir
# Can create multiple directories and multiple levels of dirs too
$ mkdir -p /target/{sub1, sub2}/{subsub1, subsub2}
ifconfig is dead, use ip instead
# basic command to see addresses in colour
ip -c a
Disk Usage, Disk Free space
NCDU - disk space usage checker
# install
sudo apt-get install ncdu
# run with
ncdu
du and df
- Finding usage of current directory + files as a single value
du -sh .
# to find just in the current directory per folder
du -h --max-depth=1
- Finding free space
df
Xargs
Xargs can be used to pipe a list of results into a command - for example find a list of directories and then for each one xargs into a subsequent command (e.g. helm dependency update)
netstat
# netstat looking for a particular port number
netstat -laptenu | grep 20005
Lookup hostname from IP address
# does a lookup on DNS
nslookup <ip address>
# hostname doesn't always work
hostname -a <ip address>
File Permissions
Give user,group and other permissions to read, write and execute
chmod ugo+rwx filename
# simply make a file executable
chmod +x filename.sh
- CHMOD calculator https://chmod-calculator.com/
Common CHMODs
- 777 - all permissions
- 644 - R/W for owner, R for others
- 755 - RWX for owner, RX for others
Find utility
# find jpg files in the current directory
find . -name '*.jpg'
# find in the current directory files modified in the last minute
find . -maxdepth 1 -mmin -1
# find with date details and ordering by date
find . -mmin -15 -printf "%T@ %Tc %p\n" | sort -n
# find .log files and then copy them to ~/someDir
find . -name "*.log" -mmin -45 -exec cp {} ~/someDir \;
# find dirs without a certain filename
find base_dir -mindepth 2 -maxdepth 2 -type d '!' -exec test -e "{}/cover.jpg" ';' -print
# find and delete - good for deleting lots of files where rm stops working
find . -name "simulation.log" -delete
# find with multiple matches (from a bash script)
list_of_files="$(find . -type f -name "filename1-*" -or -name "*-filename2")"
# find files where we have .blah and a corresponding .blah.log - finds cases of missing .log files and counts them
find . -name "*.blah" '!' -exec test -e "{}.log" ';' -print | wc -l
# some more examples
<https://geekflare.com/linux-find-commands/>
-
find can also be combined with xargs and in some cases this can be efficient to batch the subsequent commands - https://stackoverflow.com/questions/896808/find-exec-cmd-vs-xargs
- With -exec you can end by + instead of \; to batch but may not be the most portable way of writing it.
List files in directories in a Tree
# Install if not available on your machine
# List all files and directories including hidden files (-a), to 2 levels with size of each file
tree -a -L 2 -s
Symbolic links
# Create a symbolic link
ln -s /path/to/original /path/to/symlink
# List all symbolic links in a directory
ls -l | grep ^l
# List all symbolic links in a directory and their targets
ls -l | grep ^l | awk '{print $9 " -> " $11}'
# Remove a symbolic link
rm /path/to/symlink
unlink /path/to/symlink
Word Counts - find number of files in dir
- Word Count wc with lots of use cases and examples - https://shapeshed.com/unix-wc/
# count the number of files in a dir
ls -l | wc -l
Grep
Basic command format is:
grep [options] [pattern] [file]
#If you have the output "Binary file (standard input) matches" whengrep something you know is text,
# you can force grep to treat everything as text using -a
grep -a SomeString log.txt
# other forms of this option: -a, --text, '--binary-files=text'
# example of counting the occurrences
grep -o SOMESTRING myFile.txt | wc -l
Other options
- -i: performs a case-insensitive search.
- -n: displays the lines containing the pattern along with the line numbers.
- -v: displays the lines NOT containing the specified pattern.
- -c: displays the count of the matching patterns.
- -r: recursive matches through sub dirs
- -L: display files NOT matching the pattern
- -o: matches only not the full lines
- –include=*.cpp: include files matching the pattern after the = (NB may/may not need the escape wildcard)
Grep to find text within files
- GNU manual for Grep - https://www.gnu.org/savannah-checkouts/gnu/grep/manual/grep.html#index-_002d_002dno_002dmessages
find . -name "*.edi" -exec grep -H -E -o -c "SomeString" {} \;
find . -name "*.edi" -exec grep -H -E -o -c "SomeString" {} \;
# Find files of a particular name not containing a string - bit at the end is to look for count 0
find . -name "*.edi" -exec grep -H -E -o -c "SomeString" {} \; | grep 0
# This is a really nice way to find files of a particular type containing WITHTHISSTRING but not containing NOTTHISSTRING
# The inner grep feeds the filenames of the matches into the outer grep
# -l is to suppress the normal output which includes the matching string
# -L is to find things that DON'T match
grep -rL "NOTTHISSTRING" $(grep -rl WITHTHISSTRING '.' --include=*.cpp)
# Example for finding a lib with a certain symbol
for lib in `find . -name "*.so"` ; do grep "someSymbol" $lib >/dev/null; if [ $? -eq 0 ]; then echo $lib; fi done
# Finding a process with grep and filtering your grep from the result
ps aux | grep some_process | grep -v grep
Grep patterns
# Example using grouping with alternative matches
$ grep -E "(GPL|General Public License)" GPL-3
Output:
The *GNU General Public License* is a free, copyleft license for...
Developers that use the GNU *GPL* protect your rights with two steps: ...
Working with yaml and json
- https://github.com/mikefarah/yq yq utility for the commandline
- https://github.com/jqlang/jq
System Suspend from commandline
Ubuntu on a netbook
https://wiki.ubuntu.com/HardwareSupport/Machines/Netbooks
Docker Installs for Linux - Ubuntu
-
https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-docker-ce
- Add the repo for Docker to the Ubuntu install
-
Install Docker
- Docker Daemon info - https://docs.docker.com/config/daemon/
#once the repos are setup - install docker-ce
sudo apt-get install docker-ce
# These commands will download the docker images and run a container
sudo docker run hello-world
sudo docker run -it ubuntu bash
Example of the output from the hello world container
Hello from Docker! This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
- The Docker client contacted the Docker daemon.
- The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64)
- The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading.
- The Docker daemon streamed that output to the Docker client, which sent it to your terminal.
Mini Cheatsheet
## List Docker CLI commands
docker
docker container --help
## Display Docker version and info
docker --version
docker version
docker info
## Execute Docker image
docker run hello-world
## List Docker images
docker image ls
## List Docker containers (running, all, all in quiet mode)
docker container ls
docker container ls --all
docker container ls -aq
Learning Docker
- Overview - https://docs.docker.com/engine/docker-overview/
- Getting Started - https://docs.docker.com/get-started/#containers-and-virtual-machines
- Developing with Docker - https://docs.docker.com/develop/#develop-new-apps-on-docker
- Java workshop with Docker - https://github.com/docker/labs/tree/master/developer-tools/java/
Docker Compose
https://docs.docker.com/compose/install/
Docker compose is a tool to scale up docker containers using a yaml file to describe the deployment.
docker-compose stop # stop container
docker-compose down -v # stop and remove container
XHCI issues
- https://bbs.archlinux.org/viewtopic.php?id=236536
- https://askubuntu.com/questions/1035528/ubuntu-18-04-systemd-udevd-uses-high-cpu-conflict-with-nvidia-graphics
- https://www.maketecheasier.com/4-ways-to-get-yourself-out-of-a-ubuntu-crash/
Screenshots
- Simplest is Screenshot application bundled with ubuntu
- Also a list of options - https://www.tecmint.com/take-or-capture-desktop-screenshots-in-ubuntu-linux/
List of Linux Topics
- Vim - make a cheatsheet
- User permissions + groups + changing them
- tee command - multiple output destinations
- hard links vs soft links + how files are deleted
- cheatsheet of file structures /bin /dev /etc
- df du -h option
- cheatsheet for find
- more and less cheatsheet
- wc wordcount util
- grep cheatsheet
- cut, split, tail cheatsheet
- using tail for filtering lists even output of file listing with ll
- find some file compare utilities - diff comp comm
- sed awk cheatsheet
- Need to know the vim commands for this too
- tar gzip option j-> bzip2
Vim Cheatsheet
- VIM Cheatsheet - https://vim.rtorr.com/
- https://vimsheet.com/
General text manipulation
# Cutting, copying and pasting lines
yy # copy
2yy # copy 2 lines
dd # cut
p # paste after
P # paste before
# Finding
/searchstring
- Link to VIM searching page - https://vim.fandom.com/wiki/Searching
Less Cheatsheet
# Navigating within less
g - jump to beginning
G - jump to end
/someString - search for "someString" and highlight occurrences n next
occurrence N prev occurrence