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. (You wouldn’t want a local script named (say) “ls” to override the real ls command.)

Pass to bash

bash will interpret its argument as the name of a script and run it.

$ bash myscript
Run in current shell with “.” or source

The preceding methods run your script as an independent entity that has no effect on your current shell.[22] 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 source or “.” command:

$ . myscript
$ source myscript

[22] That’s because the script runs in a separate shell (a subshell or child shell) that cannot alter the original shell.

Get Linux Pocket Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.