Skip to Main Content
Linux Pocket Guide
book

Linux Pocket Guide

by Daniel J. Barrett
February 2004
Beginner content levelBeginner
200 pages
5h 40m
English
O'Reilly Media, Inc.
Content preview from Linux Pocket Guide

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

bash will 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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Pocket Guide, 2nd Edition

Linux Pocket Guide, 2nd Edition

Daniel J. Barrett
Linux in a Nutshell, 6th Edition

Linux in a Nutshell, 6th Edition

Ellen Siever, Stephen Figgins, Robert Love, Arnold Robbins

Publisher Resources

ISBN: 9780596806347Errata Page