Creating a Shell Script
Linux is a versatile operating system. One aspect of its versatility is that it can be moved from one platform to another with a minimum amount of effort. Linux also enables you to build and name your own commands. The commands that you develop are called shell script. A shell script is a file made up of Linux commands. It is usually located in the user’s home directory and can be run by entering the filename.
Tasks that you perform on a daily basis might be repetitive and involve using many commands. By making a shell script that includes these commands in the proper sequence, you can shorten and simplify your work.
Commands that are used in combination to perform common and repetitive tasks can be grouped together and placed in a file to create a shell script. By using the echo command, you can also include descriptive comments, printed to the screen, that clarify the output from your script.
Your file is made executable by using the chmod command. Once the file is executable, the filename can be typed at the command line and all of the commands in the file are executed in the order in which they were placed in the file. The shell script runs in a separate shell from your login shell.
A shell script can be as simple or as complex as you choose to make it. In advanced shell scripts, or shell programs, programming structures such as loops and conditional statements can be included.
TASK: Creating a Shell Script File
- Enter vi mylist to create a new file in the vi editor named mylist.
- In insert mode, type # Directory Shell Script to enter a comment to designate that this is a shell script. A # symbol is required as the first character in a shell script.
- Enter the following lines in your shell script:
echo “The system operator and number of users is:”
echo “ “
echo “Today’s date is:”
echo “ “
The first line echoes the specified text to the screen. The who -q command lists the operator’s name and the number of system users. The echo commands followed by two quotes place an empty line on the screen to separate the output.
4. Save the file and exit the vi editor.
Making Shell Scripts Executable
Before you can run your shell script, you need to use the chmod command t change permissions on the file. Whoever you want to be able to run the script file needs to have executable (x) permission to the file.
To force the system to look in the current directory rather than the /bin directory for the command, precede the command with . / notation. The /bin directory is the default location for shell scripts to be run form.