The first line of a shell script is special; it is used to specify the shell that the script should be under. This line should begin with a pound sign followed by an exclamation mark, #!. To indicate the shell, we then give the full path to the shell. When the Linux kernel sees the first two characters of a file are #!, it will look on the rest of the line for the full pathname of the interpreter to use to run the program. We will be using the bash shell, which is located at /bin/bash.
We can use the echo command to display basic text message. By default, the echo command does not require quotes to delineate the string. However, it is a good idea to use quotes to delineate the text string if single quotes will be used in the string in order to make sure they appear properly in the output.
Let’s make our very first script, and call it hello_world.sh. This script will contain the classic Hello World program.
echo “Hello World!”
Before we run the script, we need to make the script executable. To make the script executable, we enter the command chmod +x followed by the name of the script. Thus, to make our new script executable, we enter the command chmod +x hello_world.sh on the command line. To run the shell, we enter ./hello_world.sh at the command line. Prefixing the name of the shell script with ./ is necessary if the script is not in a folder that is indicated in the $PATH variable.
Let’s create a new script and call it echo_test.sh. The script should contain the following code:
echo “Mirab, with sails unfurled.”
echo “Shaka, when the walls fell.”
echo -n “Greetings, ”
echo “Professor Falken.”
For example, the orientation.sh script below quickly lists out some basic information about the current shell session.
echo -n “username: ”
echo -n “hostname: ”
echo -n “date: ”
echo “terminal: ”
# Al Jensen
# Prints working directory
echo -n “Working Directory: ”
# Al Jensen
# illustrate the printf command
# %s specifier is for strings
printf “%s\n” “Are we having fun yet?”
# %d specifier is for decimals
printf “The secret of life is %d” 42