Bash Scripting
Description
To create a bash script, you start by creating a text file.
Syntax
nano our_script.sh | Create text file with extension .sh meaning bash shell |
Open your file and start writing your bash script | |
#!/bin/bash | Init bash interpreter and setup path. Must be the first line with no spaces. |
Anything you run after this command will be interpreted as a normal shell command | |
You could also use other interpreters like python by typing !#/usr/bin/python3 | |
bash our_script.sh | This will execute your bash script 'our_script.sh' |
Bash Script Example to backup all files | |
nano backup.sh | Create text file with extension .sh |
Open your file and start writing your bash script | |
#!/bin/bash | Init bash interpreter and setup path. Must be the first line with no spaces. |
tar -czf backup.tar.gz ~/{Documents,Downloads,Desktop,Pictures,Videos} 2>/dev/null |
GZip the specified folders into a new archive file called backup.tar.gz Redirect the standard error to dev/null that will basically get rid of it |
Better way of running your bash scripts | |
Go to your home directory | |
mkdir bin | Make a directory called bin all in lowercase |
mv ~/Desktop/backup.sh ~/bin/ | Move all your bash scripts into the bin folder |
Go to your bin directory | |
chmod +x backup.sh | Give executable permissions to bash script backup.sh |
You have to edit the shell search path to include the bin folder | |
nano .bashrc | Open the .bashrc file for editing |
Scroll down in the file and add this line | |
PATH="$PATH:$HOME/bin" | The bin folder will be added to our path |
You have to restart your session for this change to take effect | |
echo $PATH | When we echo the path, we will see the bin folder added to the list of folders |
Running the bash script from anywhere now will work |