One of the most strong side of the Unix and Linux operating system is their scripting ability and features. Unix and Linux systems generally uses
bash as default shell and scripting facility. In this tutorial we will look how to create script and run scripts in bash shell.
Creating A Script File
Writing scripts that will run periodically needs to save script into a file. Script file contains same commands as in 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 starts 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 comment that have no effect.
Making Script File Executable
After creating script file it should be make executable to run with the file name. If it is not made executable it can be interpreted by bash executable. Lets make script file executable
chmod u+x clean.sh
u (user) means 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 remove 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 correct file for the file.
Difference Between Single and Double Quote
To express string variable quotation is used in bash. There is two type of quote named single and double Single quote
'This is single $quoted' makes nothing special. But using double
"This is double $quoted" makes
$ and similar operator usable. Here $quoted is a variable and will be interpreted.