One of the most strong sides of the Unix and Linux operating system is its scripting ability and features. Unix and Linux systems generally use bash as default shell and scripting facility. In this tutorial, we will look at how to create a script and run scripts in the bash shell.
Creating A Script File
Writing scripts that will run periodically needs to save the script into a file. The script file contains the same commands as in the terminal. The difference is the file will start with a special beginning file that points to the bash binary with shee-bang (#!)
#!/bin/bash
rm -Rf /tmp
newdir="/tmp/cache"
mkdir $newdir
As you see all commands are the same but start with /bin/bash line where the script will be interpreted with this bash executable. Be cautious that if you forget ! this will make the bash interpreter path as a comment that has no effect.
Making Script File Executable
After creating a script file it should be made executable to run with the file name. If it is not made executable it can be interpreted by bash executable. Let’s make a script file executable.
chmod u+x clean.sh
Here u (user)
means the current owner of the script file and +x makes it for the current owner executable. If we change + with -like u-x it means that removes the executable flag for the file. So we can not run it directly like this
$ chmod u-x test.sh
$ ./test.sh
bash: ./test.sh: Permission denied
Now resume from where we left, after making executable it can be run directly from shell-like this but keep in mind we assume that we are in the same directory with the script file if not we should provide the correct file for the file.
./clean.sh
Difference Between Single and Double Quote
To express a string variable quotation is used in bash. There is two types of quote named single and double Single quote'This is single $quoted'
makes nothing special. But using double "This is double $quoted"
makes $
and a similar operator usable. Here $quoted is a variable and will be interpreted.