Bash scripts are very helpful in doing time-consuming tasks in very little time, the unix “bash” terminal
first, let’s write a sample bash script all bash scripts start with #!/bin/bash, so we can point the system to the right place
Here is our first bash shell script example:
#!/bin/bash
# declare STRING variable
STRING="Hello World"
#print variable on a screen
echo $STRING
Navigate to a directory where your hello_world.sh is located and make the file executable:
chmod +x hello_world.sh
Now you are ready to execute your first bash script:
./hello_world.sh
Adding colours to your bashscripts can not only make them look more appealing but also help you differentiate between things. Bash recognises colours by there ANSI escape codes (https://en.wikipedia.org/wiki/ANSI_escape_code)
some examples are
Black 0;30 Dark Gray 1;30
Red 0;31 Light Red 1;31
Green 0;32 Light Green 1;32
Brown/Orange 0;33 Yellow 1;33
Blue 0;34 Light Blue 1;34
Purple 0;35 Light Purple 1;35
Cyan 0;36 Light Cyan 1;36
Light Gray 0;37 White 1;37
Let’s make a long but simple update script that displays system info and update the system packages but also removes the old packages (saving space).
If you don’t have “screen fetch” installed, you can either skip it or just run
sudo apt install screenfetch
Let’s script some bash remember that the “#” can be used to add comments
#!/bin/bash
RED="\033[1;31m"
GREEN="\033[1;32m"
NOCOLOR="\033[0m"
echo
echo -e "step 0: ${RED}Show Splash${NOCOLOR}"
screenfetch
echo
echo -e "step 1: ${GREEN}pre-configuring packages${NOCOLOR}"
sudo dpkg --configure -a
echo
echo -e "step 2: ${GREEN}fix and attempt to correct a system with broken dependencies${NOCOLOR}"
sudo apt-get install -f
echo
echo -e "step 3: ${GREEN}update apt cache${NOCOLOR}"
sudo apt-get update
echo
echo -e "step 4: ${GREEN}upgrade packages${NOCOLOR}"
sudo apt-get upgrade
echo
echo -e "step 5: ${GREEN}distribution upgrade${NOCOLOR}"
sudo apt-get dist-upgrade
echo
echo -e "step 6: ${GREEN}remove unused packages${NOCOLOR}"
sudo apt-get --purge autoremove
echo
echo -e "step 7: ${GREEN}clean up${NOCOLOR}"
sudo apt-get autoclean
echo
Explanation
Echo command will display the progress on screen ${Green} changes the colour of the command, so it becomes more clear on the screen Screen fetch displays an ASCII graphic of the distributions LOGO on the screen (just for fun)