How to write and run Linux shell (. SH) scripts

Time:2020-11-3

Write your first shell script

Write. Sh file in GEDIT and save it as a.sh.

这里写图片描述

code:
#! /bin/bash # employ bash shell
player1=xiaoming # define a player1
player2=ken 
echo "Game start! $player1 $player2" # echo is used to printf in terminal

Call the script at the terminal, locate the directory, and then enter:

bash a.sh

这里写图片描述

See the print result as shown above.

Write the first if / else script

If / else is written as follows:
Code between if and


ls -l a.sh 

Is used to determine whether the a.sh file exists in the current directory. The basic formats for if and else are as follows,

if command ; then
code1
else
code2
fi

这里写图片描述

The result of the terminal call is as follows. You can see the output


ls return true

这里写图片描述

Let’s look at an if / else script

In the following script, if / else format is consistent with the above format. Focus on the command between if and; and start with [, followed by four parameters $1, =, me,]

这里写图片描述

The output results are as follows:

这里写图片描述

Use = to determine whether the input string is equal to me. Other common judgment parameters are shown in the figure below:

这里写图片描述

Look at a for loop

The format of the for loop is as follows:

这里写图片描述


#! /bin/bash # employ bash shell
for num in 1 2 3 4 5 six
do 
  echo "num=$num"

for(( num=1; num<7; num++)) # method2
do 
 echo "num=$num"
done

while Loop

The basic format of the while loop is as follows:

这里写图片描述

这里写图片描述


#! /bin/bash

i=7
j=10
while [ $i -lt $j ] 
do
  echo "num1 = $i, num2=$j"
  ((i++))
done

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

Linux system uses snap to install JDK

What is snap? snapIt is a new way of software package management. It is similar to a container. It has all the files and libraries of an application, and each application is completely independent. So the advantage of using snap package is that it solves the dependency problem between applications and makes it easier to […]