Friday, October 9, 2009

Linux - Bash Shell Scripting - Introduction

One of the more powerful features of Unix systems and the shells is the ability to write shell programs, i.e., programs which are executed by the shell interpreter in order to perform useful commands or perform some task. These programs are called shell scripts, scripts, or script files. Shell scripts are a way of automating commonly performed commands or a complex set of commands.

Complete books have been written about shell scripting, and it is not something we can cover in a few blog posts. This will be a basic introduction, and you are referred to the online guides and tutorials for more information.

A script file is a text file, and the first line is usually supposed to be

#!/usr/bin/env bash

if the shell script is designed to be executed by the Bash shell. If you are using a different shell to write your script (e.g., the Korn shell), then set the first line to point to the Korn shell's binary image (usually it is in the /bin directory; e.g., /bin/ksh). This will ensure that the correct shell is loaded and used to execute the shell script regardless of what particular shell the user may be running.

Note that in shell scripts, # lines are comments, just as // are comments in C++. Any character from the # symbol to the end of the line is ignored by the shell interpreter. Typically shell scripts are given a .sh extension to let the user know it is a shell script, but this is not necessary for it to run.

Summary
  • Shell scripts are text files that automate tasks. You can put any command in it that you can type in the shell prompt.
  • The commands will execute sequentially, just as in most programming languages.
  • All shell scripts must start with the location of the bash install, "#!/usr/bin/env bash,  as the first line.
  • Lines beginning with # are comments.
  • Typically shell scripts are given a .sh extension to let the user know it is a shell script, but this is not necessary for it to run.

2 comments:

  1. Just a note that the shebang line is probably better as "#!/usr/bin/env bash". Bash is not guaranteed to be in /bin or /usr/bin but env is almost always symlinked to both (mainly to support this convention) so using "#!/usr/bin/env bash" is more portable across distributions.

    ReplyDelete