Learn shell script – P1

Tram Ho

1. Introduction

What is a shell script

A shell command is a computer program designed to run or execute by a Unix shell by a command line interpreter.

The set of shell commands written in a file ending in .sh is Shell Scripts , for example, with the content of the file named first.sh :

  • #!/bin/sh always written in the first line of the file, not the comment, but it is telling the operating system shell interaction that it is a shell program.
  • In some cases, the first.sh file needs to be granted permission to execute the contents of it. chmod 755 first.sh (chmod is an unix command).
  • The string "Hello World" is the argument, the shell echo command is used to print a string passed .

=> Instead of running the command line shell right in the terminal (unix):

=> We can execute the following command line inside a file first.sh :


  • Automation of operations is performed regularly.
  • Run the command sequence as a command.
  • It can be implemented in any Unix-like operating system without any modification.


  • Performance is slow compared to any programming language
  • A new process is launched for almost every shell command to be executed.

2. Use variables

The string passed in the above example can be replaced by the declared variable :

  • MY_MESSAGE is the custom variable name you set, as long as the MY_MESSAGE format is combined with an underscore
  • While echo accepts multiple input arguments (no need to use " ), a variable can only store one string value, so it should be enclosed in quotation marks "Hello World" .

It is also possible to interactively set the variable value entered from the keyboard with the read command:

Some common command line parameters:

  • $0 : Name of the script file.
  • $1 -> $9 : The parameters passed
  • $# : The number of parameters passed
  • $* : List of passed parameters ( $# and $* will not include $0 )

The scope of variable usage should also be considered:

An myvar2.sh variable will have an empty value (e.g., myvar2.sh ):

=> the result is:

You will not be able to directly use declarative variables from outside the file:

Unless you use export

It is also impossible to directly use variables inside external files:

=> when the shell script is finished running, its environment will be destroyed (that is, when calling variables in shell scripts externally such as terminals, variables in that shell will be empty)

So also need to use export MYVAR inside the file, but we can use it . :

use . We will not need to export variables both inside and outside the file. From here you can understand the principle of using environment variables in .profile or .bash_profile files.

Share the news now

Source : Viblo