Bash script tutorial
Let’s create our first simple shell script
#!/bin/sh
# This is a comment!
echo Hello World # This is a comment, too!- The first line tells Unix that the file is to be executed by
/bin/sh. This is the standard location of the Bourne shell on just about every Unix system. If you’re using GNU/Linux, /bin/sh is normally a symbolic link to bash (or, more recently, dash). - The second line begins with a special symbol:
#. This marks the line as a comment, and it is ignored completely by the shell. - The only exception is when the very first line of the file starts with
#!(shebang) - as ours does. This is a special directive which Unix treats specially. It means that even if you are using csh, ksh, or anything else as your interactive shell, that what follows should be interpreted by the Bourne shell. - Similarly, a Perl script may start with the line
#!/usr/bin/perlto tell your interactive shell that the program which follows should be executed by perl. For Bourne shell programming, we shall stick to#!/bin/sh. - The third line runs a command:
echo, with two parameters, or arguments - the first is"Hello"; the second is"World". - Note that
echowill automatically put a single space between its parameters. - To make it executable, run
chmod +rx <filename>
Variables
Let’s look back at our first Hello World example. This could be done using variables. Note that there must be no spaces around the “=” sign: VAR=value works; VAR = value doesn’t work. In the first case, the shell sees the “=” symbol and treats the command as a variable assignment. In the second case, the shell assumes that VAR must be the name of a command and tries to execute it.