O'Reilly logo

Linux Pocket Guide, 2nd Edition by Daniel J. Barrett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required