The bash command uses detail

  • 2020-12-26 06:50:02
  • OfStack

Using bash as the standard on Linux basically describes the processing and execution of text such as the vi editor with the ".sh "extension.

Like programming 1, it has many functions, such as variables, functions, and arithmetic processing, so if you are a small program, you can write it in bash.

In addition, since bash is executed by shell, it is also known as the shell script.

Create 1 shell script

Let's start by creating a simple script that will "Hello World! !" Output to the console.

Use the vi command to create a new file.


$ vi hello.sh

After opening the editor, write as follows.


#!/usr/bin/bash
echo "Hello World!!"
exit 0

"#!" on line 1 / usr/bin/bash "indicates that it is an shell script using bash.

Line 2 describes the statement to be executed.

Finally, exit bash using "exit 0". The parameter 0 indicates the normal end.

After creating the file, execute the shell script using the bash command.


$ bash hello.sh

Execution Results:


Hello World!!

Hello World !! Is the output

In addition to bash, the command when executing the shell script also changes execution permissions to run with "./ ".


$ chmod 755 hello.sh
$ ./hello.sh

There is one way to do this using the sh command.


$ sh hello.sh

The shell script can be annotated and programmed.

Comments can be written after "#".


#!/usr/bin/bash
echo "Hello World!!"
# Finish processing. 
exit 0

The Shell script can define variables and assignments.


#!/usr/bin/bash
 
num=100
PI=3.14
STR1="Hello"
str_2="World!!"
 
echo ${num}
echo ${PI}
echo ${STR1}
echo ${str_2}
 
exit 0

Variables can be alphanumeric characters, such as uppercase and lowercase letters, numbers, and underscores (_).

When assigning a value to a variable, write it as variable = value.

Note that placing Spaces before and after "=" results in an error.

In addition, when accessing variables, you need to add "$" before the variable name, such as" ${variable} ", enclosing variables in "{}".

Input and output


#!/usr/bin/bash
 
read AGE
echo "ege=$AGE"
 
exit 0

Execution Results:


30
ege=30

read stores the input from the console into the variable specified in the parameter.

The variables specified by read can be called ordinary variables.


Related articles: