Creating and Running Shell Scripts
To create a shell script, simply put bash commands into a file as you would type them. To run the script, you have three choices:
- Prepend #!/bin/bash and make the file executable
This is the most common way to run scripts. Add the line:
#!/bin/bash
to the very top of the script file. It must be the first line of the file, left-justified. Then make the file executable:
$ chmod +x myscript
Optionally, move it into a directory in your search path. Then run it like any other command:
$ myscript
If the script is in your current directory, but the current directory “.” is not in your search path, you’ll need to prepend “./” so the shell finds the script:
$ ./myscript
The current directory is generally not in your search path for security reasons.
- Pass to bash
bashwill interpret its argument as the name of a script and run it.$ bash myscript
- Run in current shell with “.”
The preceding methods run your script as an independent entity that has no effect on your current shell.[21] If you want your script to make changes to your current shell (setting variables, changing directory, and so on), it can be run in the current shell with the “.” command:
$ . myscript
[21] Technically, it runs in a separate shell (a subshell or child shell) that inherits the attributes of the original shell, but cannot alter them in the original shell.