Shell Script Basics
- A shell script is a plain-text file that contains shell commands. It can be executed by typing its name into a shell, or by placing its name in another shell script.
- To be executable, a shell script file must meet some conditions:
- The file must have a special first line that names an appropriate command processor.
#!/bin/bash
If this example doesn't work, you will need to find out where your Bash shell executable is located and substitute that location in the above example. Here is one way to find out:
$ whereis bash - The file must be made executable by changing its permission bits. An example:
$ chmod +x (shell script filename)
- The file must have a special first line that names an appropriate command processor.
- A shell script file may optionally have an identifying suffix, like ".sh". This only helps the user remember which files are which. The command processor responsible for executing the file uses the executable bit, plus the file's first line, to decide how to handle a shell script file.
- One normally executes a shell script this way:
$ ./scriptname.sh
This special entry is a way to tell the command processor that the desired script is located in the current directory.
First Shell Script
- This will get you past the details of writing and launching a simple script.
- Choose a text editor you want to use. It can be a command-line editor like emacs, pico or vi, or an X Windows editor if you have this option.
- Run your choice of editor and type the following lines:
#!/bin/bash echo "Hello, world."
NOTE: Be sure to place a linefeed at the end of your script. Forgetting a terminating linefeed is a common beginner's error. - Save the file in the current working directory as "myscript.sh".
- Move from the text editor to a command shell.
- From the command shell, type this:
$ chmod +x myscript.sh - To execute the script, type this:
$ ./myscript.sh
Hello, world.
No comments:
Post a Comment