C Shell Scripting/Hello

From Wikibooks, open books for an open world
Jump to navigation Jump to search

How to create a script[edit | edit source]

Unix scripts are generally small and are designed to accomplish a single task. The simplicity of construction makes shell scripts the optimal choice automating command-line tasks . If you already know the commands that were entered to manually get to task done, the program is half finished.

The "Hello, World!" program is a good starting point to learn a new language such as C shell. We have to first learn the Unix command to print text to the console which is called echo. Just type "echo" followed by what you want to print and it will be print when you run the command.

$ echo Hello, World!
Hello, World!

Now let's create a text file that will be our script to say hello. We will use a program called nano which is common text editor on Unix. But any editor will do. You noticed we simply named the file "hello" since in Unix the file extension is not required. Although if you wanted an extension, ".csh" is commonly used.

$ nano hello

The first line of our script is called a shebang. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/csh. All scripts under Unix execute using the interpreter specified on a first line. By including the shebang line, you can run the program like a compiled application and it will automatically find the shell program to run it. Noticed that we are using a "-f" option when specifying the path to C shell. This prevents running the user's setup file which needlessly slows and complicates the script.

The second line is the echo command from above which is the actual program logic.

#!/bin/csh -f
echo Hello, World!


Now we can save the file and exit the editor. In the case of nano, press the control-X key.

In Unix we must adjust file permissions to be able to execute the script. The chmod command is used to mark the file executable.

$ chmod +x hello

Now we can actually run the script. Remember to include the directory in front of the file name. If you are currently in the same directory as the script you must still include the current directory ("./")

$ ./hello
Hello, World!

Lessons[edit | edit source]

  1. All scripts should begin with a interpreter directive called a shebang line.
  2. In Unix scripts must be given an executable permission to be runnable.
  3. The echo command is commonly used to print in a script.