Useful Examples and snippets

Important commands

  • head -n 1 to get the first token in a string

  • tail -n 1 to get the last token in a string

  • wc -l count the number of files in a file or a stream

  • wc -w count the number of words (tokens) in a file or a stream

  • tr " " "\n" replace spaces with new lines in a string or stream

  • tr "," "\n" replace commas with newlines in a string or stream

Capture Earlier or latest Files, or directories

latest_node=$(ls /lib/modules -At | head -n 1)

earliest_node=$(ls /lib/modules -At | tail -n 1)

echo "python javascript C++" | tr " " "\n" | head -n 1  # get the first token, python
echo "python javascript C++" | tr " " "\n" | tail -n 1  # get the last token, C++

Redirection and useful pipelines

# redirect errors and warnings to the null device
sudo apt update 2> /dev/null

# count the linux packages in an upgrade
linux_packages=$(apt list --upgradable 2>/dev/null  | grep -e "^linux-.*" | wc -l)

Modules installation with Kernel Upgrades

sudo apt update > /dev/null # Get Available Upgrades from the ubuntu repo
linux_packages=$(apt list --upgradable 2>/dev/null  | grep -e "^linux-.*" | wc -l) # count the linux packages
if [[ $linux_packages -gt 0 ]] ; then kernel_update=1; fi  # Set the Kernel upgrade flag if needed
sudo apt upgrade 2>/dev/null # promt user and confirm upgrade
sudo apt-get -y autoremove # remove the previous kernel if needed
if [[ $? -eq 0 && $kernel_update ]]; then echo "Run wifi script"; fi # Execute Wifi driver script if needed