Linux Shell script common sense, simple use of script

Sometimes you need to create a lot of directories at once, or some batches of repeated operations, we do n’t want a lot of repeated operations, so there is a script

Shell script

The statements in the script will be executed when the script is opened, which is equivalent to we directly input on the console. It is worth noting that variables, flow control statements, or some other operations can be introduced in the script

Create a simple HelloWorld script

We need to create a file to write our script. It is worth noting that the execution of the binary file has nothing to do with the suffix name, that is, we can not write the suffix name, which is also allowed, but in order to facilitate us to confirm what file this is, we It's better to have a suffix name

sh indicates that this is a shell script, and the advantage of this is that vim will automatically recognize that this is a script, and then highlight some syntax symbols to make the editing interface look good

Create new file

vim hello.sh

Convention interpreter

#!Is a special symbol that tells the system where to find the interpreter of the script, we add in the first line of the file

#!/bin/bash

echo statement

echo is responsible for outputting a line to the console, we output a line of strings to try

echo "Hello World!"

The whole is hello.shas follows
Insert picture description here
ESC, colon, wq, enter, save and exit!

Execute script

Before executing the script, we need to assign permissions to the script

chmod 777 hello.sh

Execute scripts need to play in the current directory ./脚本名.sh, attention ./can not be omitted, otherwise the system will go to look for environment variables hello.sh

./hello.sh

Insert picture description here

Create a folder with a script

The statements in the script will be equivalent to the input to the console . We can simply create a folder and change the content of hello.sh to

#!/bin/bash

echo "Hello World!"

ls
echo "creat a new dir named dir1"
mkdir dir1
ls

Insert picture description here
Execute the script again, you can see

The first line of the output hello
second line of the output lsresult of the command to print the current directory file
third line is the information that we echo the output of
the fourth row Print directory information again, do comparison
Insert picture description here
the same way you can delete a folder, the contents of the script To

#!/bin/bash

echo "Hello World!"

ls
echo "remove dir1"
rm -rf dir1
ls

Insert picture description here
It turned out that dir1 was removed
Insert picture description here

Published 262 original articles · won 11 · 10 thousand views

Guess you like

Origin blog.csdn.net/weixin_44176696/article/details/105229169