Creating scripts in linux

Writing Our First Script and Getting It to Work

To successfully write a shell script, we have to do three things:

  1. Write a script
  2. Give the shell permission to execute it
  3. Put it somewhere the shell can find it

Writing a Script

A shell script is a file that contains ASCII text. To create a shell script, we use a text editor. A text editor is a program, like a word processor, that reads and writes ASCII text files. There are many, many text editors available for Linux systems, both for the command line and GUI environments. Here is a list of some common ones:

Name Description Interface
vi, vim The granddaddy of Unix text editors, vi , is infamous for its obtuse user interface. On the bright side, vi is powerful, lightweight, and fast. Learning vi is a Unix rite of passage, since it is universally available on Unix-like systems. On most Linux distributions, an enhanced version of vi called vim is provided in place of vi. vim is a remarkable editor and well worth taking the time to learn it. command line
Emacs The true giant in the world of text editors is Emacs originally written by Richard Stallman. Emacs contains (or can be made to contain) every feature ever conceived of for a text editor. It should be noted that vi and Emacs fans fight bitter religious wars over which is better. command line
nano nano is a free clone of the text editor supplied with the pine email program. nano is very easy to use but is very short on features compared to vim and emacs . nano is recommended for first-time users who need a command line editor. command line
gedit gedit is the editor supplied with the GNOME desktop environment. gedit is easy to use and contains enough features to be a good beginners-level editor. graphical
kwrite kwrite is the «advanced editor» supplied with KDE. It has syntax highlighting, a helpful feature for programmers and script writers. graphical

Let’s fire up our text editor and type in our first script as follows:

Clever readers will have figured out how to copy and paste the text into the text editor 😉

This is a traditional «Hello World» program. Forms of this program appear in almost introductory programming book. We’ll save the file with some descriptive name. How about hello_world ?

The first line of the script is important. It is a special construct, called a shebang, given to the system indicating what program is to be used to interpret the script. In this case, /bin/bash . Other scripting languages such as Perl, awk, tcl, Tk, and python also use this mechanism.

The second line is a comment. Everything that appears after a «#» symbol is ignored by bash . As our scripts become bigger and more complicated, comments become vital. They are used by programmers to explain what is going on so that others can figure it out. The last line is the echo command. This command simply prints its arguments on the display.

Setting Permissions

The next thing we have to do is give the shell permission to execute our script. This is done with the chmod command as follows:

The «755» will give us read, write, and execute permission. Everybody else will get only read and execute permission. To make the script private, (i.e., only we can read and execute), use «700» instead.

Putting It in Our Path

At this point, our script will run. Try this:

We should see «Hello World!» displayed.

Before we go any further, we need to talk about paths. When we type the name of a command, the system does not search the entire computer to find where the program is located. That would take a long time. We see that we don’t usually have to specify a complete path name to the program we want to run, the shell just seems to know.

Well, that’s correct. The shell does know. Here’s how: the shell maintains a list of directories where executable files (programs) are kept, and only searches the directories on that list. If it does not find the program after searching each directory on the list, it will issue the famous command not found error message.

This list of directories is called our path. We can view the list of directories with the following command:

This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is entered. In our first attempt to execute our new script, we specified a pathname («./») to the file.

We can add directories to our path with the following command, where directory is the name of the directory we want to add:

A better way would be to edit our .bash_profile file to include the above command. That way, it would be done automatically every time we log in.

Most Linux distributions encourage a practice in which each user has a specific directory for the programs he/she personally uses. This directory is called bin and is a subdirectory of our home directory. If we do not already have one, we can create it with the following command:

If we move our script into our new bin directory we’ll be all set. Now we just have to type:

Читайте также:  Kernel windows data recovery

and our script will run. On some distributions, most notably Ubuntu (and other Debian-based distributions), we will need to open a new terminal session before our newly created bin directory will be recognized.

© 2000-2021, William E. Shotts, Jr. Verbatim copying and distribution of this entire article is permitted in any medium, provided this copyright notice is preserved.

Linux® is a registered trademark of Linus Torvalds.

Источник

How to Create a First Shell Script

Shell scripts are short programs that are written in a shell programming language and interpreted by a shell process. They are extremely useful for automating tasks on Linux and other Unix-like operating systems.

A shell is a program that provides the traditional, text-only user interface for Unix-like operating systems. Its primary function is to read commands (i.e., instructions) that are typed into a console (i.e., an all-text display mode) or terminal window (i.e., all-text mode window) and then execute (i.e., run) them. The default shell on Linux is the very commonly used and highly versatile bash.

A programming language is a precise, artificial language that is used to write computer programs, which are sets of instructions that can be automatically translated (i.e., interpreted or compiled) into a form (i.e., machine language) that is directly understandable by a computer’s central processing unit (CPU).

A feature of bash and other shells used on Unix-like operating systems is that each contains a built-in programming language, referred to as a shell programming language or shell scripting language, which is used to create shell scripts. Among the advantages of using shell scripts are that they can be very easy to create and that a large number are already available in books and on the Internet for use with or without modification for a wide variety of tasks. Shell scripts are also employed extensively in the default installations of Unix-like operating systems.

A First Script

The following example, although extremely simple, provides a useful introduction to creating and using shell scripts. The script clears the monitor screen of all previous lines and then writes the text Good morning, world. on it.

All that is necessary to create this script is to open a text editor (but not a word processor), such as gedit or vi, and type the following three lines exactly as shown on a new, blank page:

Alternatively, the above code could be copied from this page and pasted to a blank page opened by the text editor page using the standard keyboard or mouse copy and paste functions.

After saving this plain text file, with a file name such as morning (or anything else desired), the script is complete and almost ready to run. Scripts are typically run by typing a dot, a forward slash and the file name (with no spaces in between) and then pressing the ENTER key. Thus, for example, if the above script were saved with the name morning, an attempt could be made to execute it by issuing the following command:

However, the script probably will not run, in which case an error message will appear on the screen such as bash: ./morning: Permission denied. This is because the permissions for the file first have to be set to executable. (By default, the permissions for new files are set to read and write only.) The problem can easily be solved by using the chmod command with its 755 option (which will allow the file creator to read, write and execute the file) while in the same directory as that in which the file is located as follows:

Now the script is ready to run by typing the following, again while in the same directory, and then pressing the ENTER key:

How It Works

The first of the three lines tells the operating system what shell to use to interpret the script and the location (i.e., absolute pathname) of the shell. The shell is bash, which is located in the /bin directory (as are all shells); thus the line contains /bin/bash. This instruction is always preceded by a pound sign and an exclamation mark in order to inform the operating system that it is providing the name and location of the shell (or other scripting language).

The second line tells the shell to issue the clear command. This is a very simple command that removes all previous commands and output from the console or terminal window in which the command was issued.

The third line tells the shell to write the phrase Good morning, world. on the screen. It uses the echo command, which instructs the shell to repeat whatever follows it. (The quotation marks are not necessary in this case; however, it is good programming practice to use them, and they can make a big difference in more advanced scripts.) In slightly more technical terms, Good morning, world. is an argument (i.e., input data) that is passed to the echo command.

As is the case with other commands used in shell scripts, clear and echo can also be used independently of scripts. Thus, for example, typing clear on the screen and pressing the ENTER key would remove all previous commands and output and just leave a command prompt for entering the next command.

It Doesn’t Work!

If the phrase Good morning, world. does not appear at the top of the screen, there are several possible reasons: (1) an error was made in copying the code (such as omitting the word echo), (2) the name used in the command was not exactly the same as that of the file (e.g., there is an extra space or a minor difference in spelling or capitalization), (3) the period and/or forward slash were omitted (or reversed) in the command, (4) a space was inserted after the period or slash, (5) the file is not a plain text file (typically because a word processor was used to create it instead of a text editor), (6) the command was not issued in the same directory as that in which the file is located and (7) the permissions were not changed to execute for the owner (i.e., creator) of the file.

Читайте также:  Intel raid utility windows server 2016

It is important to avoid practicing writing and executing scripts as the root (i.e., administrative) user. An improperly written script could damage the operating system, and, in a worst case scenario, it could result in the loss of valuable data and make it necessary to reinstall the entire operating system. For this and other reasons, if an ordinary user account does not yet exist on the computer, one should immediately be created (which can be easily accomplished with a command such as adduser).

Experiments

There are a number of simple, and instructive, experiments that a curious user could do with the above example before moving on to more complex examples. They consist of revising the code as suggested below, saving the revisions (using either the same file name or a different file name), and then executing them as explained above.

(1) One is to try changing some of the wording (for example, changing the third line to echo «Good evening, folks.»).

(2) Another is to add one or more additional lines to be written to the screen, each beginning with the word echo followed by at least one horizontal space.

(3) A third is to leave a blank line between two echo lines. (It will be seen that this will not affect the result; however, a blank line can be created by just typing echo on it and nothing else.)

(4) A fourth is to insert some blank horizontal spaces. (Notice that the result will be different depending on whether the blank spaces are inserted before or after the first quotation marks. This tells something about the role of quotation marks in shell scripts.)

(5) A fifth is to execute the file from a different directory from that in which it is located. This requires adding the path of the executable script to the beginning of the command name when it is issued (e.g., ./test/morning if the file has been moved to a subdirectory named test).

(6) Another experiment would be to add some other command to the script file, such as ps (which shows the processes currently on the system), pwd (which shows the current directory), uname (which provides basic information about a system’s software and hardware) or df (which shows disk space usage). (Notice that these and other commands can be used in the script with any appropriate options and/or arguments.)

Created December 21, 2005.
Copyright © 2005 The Linux Information Project. All Rights Reserved.

Источник

How to Create Simple Shell Scripts in Linux

Creating shell scripts is one of the most essential skills that Linux users should have at the tip of their fingers. Shell scripts play an enormous role in automating repetitive tasks which otherwise would be tedious executing line by line.

In this tutorial, we highlight some of the basic shell scripting operations that every Linux user should have.

1. Create a Simple Shell Script

A shell script is a file that comprises ASCII text. We will start by creating a simple shell script, and to do this, we will use a text editor. There are quite a number of text editors, both command-line and GUI-based. For this guide, we will use the vim editor.

We will start off by creating a simple script that displays “Hello world” when executed.

Paste the following content in the file and save.

Let’s go over the shell script line by line.

  • The first line – #!/bin/bash – is known as the shebang header. This is a special construct that indicates what program will be used to interpret the script. In this case, this will be the bash shell indicated by /bin/bash. There are other scripting languages such as Python which is denoted by #!/usr/bin/python3 and Perl whose shebang header is is denoted by #!/usr/bin/perl .
  • The second line is a comment. A comment is a statement that describes what a shell script does and is not executed when the script is run. Comments are always preceded by the hash sign # .
  • The last line is the command that prints the ‘Hello World’ message on the terminal.

The next step is to make the script executable by assigning execute permission using the chmod command as shown.

Finally, run the shell script using either of the commands:

Create Hello World Shell Script

2. Using Conditional Statements to Execute Code

Like other programming languages, conditional statements are used in bash scripting to make decisions, with only a slight variation in the syntax. We are going to cover the if, if-else, and elif conditional statements.

Example of an if Statement Only

The if statement can be used to test single or multiple conditions. We will start off with the fundamental use of the if statement to test a single condition. The if statement is defined by the if . fi blocks.

Let’s take a look at the shell script below.

The above shell script prompts the user to provide a score that is then stored in a variable x. If the score corresponds to 70, the script returns the output “Good job!”. The comparison operator == is used to test if the score entered, which is stored in the variable x, is equivalent to 100.

if Statement in Shell Script

Other comparison operators you can use include:

  • -eq – Equal to
  • -ne – Not equal to
  • -lt – Less than
  • -le – Less than or equal to
  • -lt – Less than
  • -ge – Greater than or equal to

For example, the if-statement block below prints out ‘Work Harder’ if the input score is any value less than 50.

if Statement in Shell Script

Example of an if-else Statement

For situations where you have 2 possible outcomes: – whether this or that – the if-else statement comes in handy.

Читайте также:  Кэнон 3010 драйвер линукс

The script below reads the input score and checks whether it is greater than or equal to 70.

If the score is greater than or equal to 70, you get a ‘Great job, You passed!’ message. However, if the score falls below 70, the output ‘You failed’ will be printed.

if-else statement in Shell Script

Example of an if-elif-else Statement

In scenarios where there are multiple conditions and different outcomes, the if-elif-else statement is used. This statement takes the following format.

For example, we have a script for a lottery that checks if the number entered is either 90, 60 or 30.

if-elif-else statement

3. Using the If Statement with AND Logic

You can use the if statement alongside the AND logic operator to execute a task if two conditions are satisfied. The && operator is used to denote the AND logic.

5. Using the If Statement with OR Logic

When using the OR logic, that is represented by || symbol, either one of the conditions needs to be satisfied with the script to give the expected results.

If statement with OR logic

Use Looping Constructs

Bash loops allow users to perform a series of tasks until a certain result is achieved. This comes in handy in performing repetitive tasks. In this section, we shall have a peek at some of the loops which you’d also find in other programming languages.

While loop

This is one of the easiest loops to work with. The syntax is quite simple:

The while loop below lists all the numbers from 1 to 10 when executed.

Let’s disscuss the while loop:

The variable counter is initialized to 1. And while the variable is less than or equal to 10, the value of the counter will be incremented until the condition is satisfied. The line echo $counter prints all the numbers from 1 to 10.

While loop in Shell Script

For loop

Like the while loop, a for loop is used to execute code iteratively. I.e. repeat code execution as many times as possible defined by the user.

The for loop below iterates through 1 right through 10 and processes their values on the screen.

For loop in Shell Script

A better way to achieve this is to define a range using the double curly braces < >as shown instead of typing all the numbers.

Bash Positional Parameters

A positional parameter is a special variable that is referenced in the script when values are passed on the shell but cannot be assigned. Positional parameters run from $0 $1 $2 $3 …… to $9. Beyond the $9 value, the parameters have to be enclosed in curly brackets e.g $<10>, $ <11>… and so on.

When executing the script, the first positional parameter which is $0 takes the name of the shell script. The $1 parameter takes the first variable that is passed on the terminal, $2 takes the second, $3 the third and so on.

Let’s create a script test.sh as shown.

Next, execute the script and provide the first and second name as the arguments:

Bash Positional Parameter

From the output, we can see that the first variable that is printed is the name of the shell script, in this case, test.sh. Thereafter, the names are printed out corresponding to the positional parameters defined in the shell script.

Positional parameters are useful in that they help you customize the data being entered instead of explicitly assigning a value to a variable.

Shell Command Exit Codes

Let’s begin by answering a simple question, What is an exit code?

Every command executed on the shell by a user or shell script has an exit status. An exit status is an integer.

An exit status of 0 implies that the command executed successfully without any errors. Anything between 1 to 255 shows that the command failed or did not execute successfully.

To find the exit status of a command, use the $? Shell variable.

An exit status of 1 points to a general error or any impermissible errors such as editing files without sudo permissions.

An exit status of 2 points to incorrect usage of a command or builtin shell variable.

The 127 exit status points to an illegal command which usually yields the ‘command not found’ error.

Find Exit Status of Command

Processing Output of Shell Commands within a Script

In bash scripting, you can store the output of a command in a variable for future use. This is also referred to as shell command substitution and can be achieved in the following ways.

For example, you can store the date command in a variable called today and call the shell script to reveal the current date.

Print Date Using Shell Script

Let’s take another example. Suppose you want to find the valid login users on your Linux system. How would you go about it? First, the list of all the users (both system, process, and login users) is stored in the /etc/passwd file.

To view the file, you’d need to use the cat command. However, to narrow down to log in users, use the grep command to search for users with the /bin/bash attribute and use the cut -c 1-10 command as shown to display the first 10 characters of the names.

We have stored the cat command to the login_users variable.

List Logged in Users

This brings our tutorial on creating simple shell scripts to an end. We hope you found this valuable.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Оцените статью