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
.

shell is a program that provides the traditional, text-only user
interface
 for Unix-like operating systems. Its primary function is to readcommands (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.

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:

#!/bin/bash
clear
echo "Good morning, world."

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:

./morning

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 toread 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:

chmod 755 morning

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

./morning

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
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.

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 namedtest).

(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) ordf (which shows disk space usage). (Notice that these and other commands can be used in the script with any appropriate options and/or arguments.)

 

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
.

shell is a program that provides the traditional, text-only user
interface
 for Unix-like operating systems. Its primary function is to readcommands (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.

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:

#!/bin/bash
clear
echo "Good morning, world."

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:

./morning

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 toread 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:

chmod 755 morning

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

./morning

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
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.

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 namedtest).

(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) ordf (which shows disk space usage). (Notice that these and other commands can be used in the script with any appropriate options and/or arguments.)

How to Create a First Shell Script的更多相关文章

  1. shell script练习

    执行脚本的几种方式: 1. sh a.sh 或者  bash a.sh  调用的是 /bin/bash 进程执行的,所以脚本不需要执行权限. 2. 直接使用绝对路径执行, /home/script/a ...

  2. 第十三章、学习 Shell Scripts 简单的 shell script 练习

    简单的 shell script 练习 简单范例 对谈式脚本:变量内容由使用者决定 [root@www scripts]# vi sh02.sh #!/bin/bash # Program: # Us ...

  3. linux基础之Shell Script入门介绍

    本文介绍下,学习shell script编程的入门知识,通过几个入门实例,带领大家走进shell script的神圣殿堂,呵呵,有需要的朋友参考下. 本文转自:http://www.jbxue.com ...

  4. 第13章 学习shell script

    由于博客园中dollar符号有别的意义,所以文中的dollar符号使用¥表示 第一个script [root@localhost script]# cat -n sh01.sh #!/bin/bash ...

  5. 学习shell script

    摘要:概述.script的编写.test命令.[]判断符号.默认变量($1...).if...then条件判断式. 一.概述 [什么是shell script] 针对shell所写的脚本,将多个命令汇 ...

  6. Shell Script Basics

    https://developer.apple.com/library/mac/documentation/OpenSource/Conceptual/ShellScripting/shell_scr ...

  7. shell 编程 && bash 简介(shell 变量、shell操作环境、数据流重导向、管线命令、shell script)

    如何学习一门编程语言 数据类型 运算符 关键字 1 认识BASH 这个shell linux是操作系统核心,用户通过shell与核心进行沟通,达到我们想要的目的.硬件.核心.用户之间的关系: 原理:所 ...

  8. shell及脚本4——shell script

    一.格式 1.1 开头 必须以 "# !/bin/bash"  开头,告诉系统这是一个bash shell脚本.注意#与!中间有空格. 二.语法 2.1 数值运算 可以用decla ...

  9. shell script

    一.shell script的编写与执行 1.shell script 的编写中还需要用到下面的注意事项: a.命令的执行是从上到下,从左到右地分析与执行 b.命令.参数间的多个空白都会被忽略掉 c. ...

随机推荐

  1. Django搭建博客记(一)

    这里记录一些 Django 搭建博客遇到的一些问题 参考书籍为 Django by Example, 这里记录与书籍内容不包含的内容. 搭建环境: 阿里云 ECS + CentOS7 一开始搭建的时候 ...

  2. 《C# 从现象到本质》出版,免费送书10本

    我的第一本书<C# 从现象到本质>已于近日正式在京东和淘宝天猫上开始销售了.至此,我的图书写作和出版活动正式告一段落.图书销售网址见下. 试读样章 京东 天猫 从看书到写书 借着图书出版之 ...

  3. Akka-Cluster(4)- DistributedData, 分布式数据类型

    在实际应用中,集群环境里共用一些数据是不可避免的.我的意思是有些数据可以在任何节点进行共享同步读写,困难的是如何解决更改冲突问题.本来可以通过分布式数据库来实现这样的功能,但使用和维护成本又过高,不值 ...

  4. springboot2.0jar包启动异常

    今天碰到一个异常: 08:44:07.214 [main] ERROR org.springframework.boot.SpringApplication - Application run fai ...

  5. JavaScript 快速入门

    JavaScript是jquery的基础, JavaScript是一种描述性语言 JavaScript的组成 :ECMAScript,BOM,DOM. JavaScript的基本结构 <scri ...

  6. Robot Framework - 一些练习

    01 - 安装Robot Framework TA环境 根据系统请选择对应的版本包来安装,下面是以Win7-64bit系统为例,来说明如何搭建一个可以运行练习三test case的RF TA环境. 1 ...

  7. DFA算法实现关键字查找(正则原理入门)

    前言:一直都这样认为“正则表达式是一个很有用的技能”,从一开始的磕磕绊绊的使用和摸索,到后来可以得心应手,这个过程离不来平时的不断学习和思考

  8. python之连接oracle模块(cx_Oracle)

    cx_Oracle模块下载地址如下: https://pypi.python.org/pypi/cx_Oracle/5.2.1#downloads 安装好之后就可以使用了,具体使用如下 #!/usr/ ...

  9. Xamarin.Android 解决打开软键盘导致底部菜单上移问题

    在界面布局中有EditText控件,该控件一旦获取焦点则打开软键盘,如果布局中有底部菜单,那么底部菜单可能会被软键盘顶在其上面,看如下效果: 解决方法:在活动绑定界面之前写上下段代码即可 Window ...

  10. Hibernate实体类注解中如何忽略某些字段的映射

    使用注解 @Transient在该字段上 例如: @Transient private int  name: 这样在映射数据表和对象关系时候就不会报在表中不存在该字段的问题: