Setting up and Running Bash scripts
Everything we have covered so far relates to using a shell interactively i.e typing in one command at a time and getting an immediate response. Just about anything you can interactively do in a shell can be put into a script to be executed. This is useful for stringing together numerous commands and creating easy repeatability.
Shell script files are denoted with the .sh extension. Creating a new script file is as easy as touch <filename>.sh or creating it in your editor of choice. Next, you want to make it executable by using chmod +x <filename>.sh.
There is a convention that the first line of your shell script should be #! /bin/bash or similar. The shebang command will tell the shell what kind of interpreter to run. While not necessary it is good practice.
There are multiple options for executing the script:
- ./<filename>.sh – most commonly used
- source <filename>.sh
- /bin/bash <filename>.sh
- bash <filename>.sh – assuming /bin is in your $PATH
- sh <filename>.sh
image: example of a simple script