Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of executing .sh file in linux

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail the methods of implementing .sh files in linux. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

1. The .sh file is a text file, and if you want to execute it, you need to use chmod adepx xxx.sh to give executable permissions.

Is it a bash script?

You can create test.sh files with touch test.sh #

Vi test.sh # Editing the test.sh file

Add content

#! / bin/bash

Mkdir test

Save exit.

Chmod aquix test.sh # gives test.sh executable permission

For example, the test,sh file is under the / home/work file

Execution

Method 1 runs under its own directory

Go to the cd / home/workwen file

Execute. / test.sh

The command creates a "test" directory under the current directory.

Method 2 absolute road strength operation

Execute / home/work/test.sh

Method 3 runs under its own directory

Sh test.sh

Final recommendation: use the

C code

1.man sh

Man sh, let's take a look at sh's introduction.

Linux.sh syntax

Introduction:

The beginning of 1

The program must start with the following line (must be placed on the first line of the file):

#! / bin/sh

Symbol #! It is used to tell the system that the parameters behind it are the program used to execute the file. In this example, we use / bin/sh to execute the program.

When writing a script is complete, if you want to execute the script, you must also make it executable.

To make writing a script executable:

Compile chmod + x filename so that you can run it with. / filename

2 comments

In shell programming, sentences that begin with # indicate comments until the end of the line. We sincerely recommend that you use comments in your program.

If you use comments, you can understand how the script works and how it works in a short period of time, even if you haven't used the script for a long time.

3 variables

You must use variables in other programming languages. In shell programming, all variables are made up of strings, and you don't need to declare variables. To assign a value to a variable, you can write:

#! / bin/sh

# assign values to variables:

A = "hello world"

# now print the contents of the variable a:

Echo "An is:"

Echo $a

Sometimes variable names are easily confused with other words, such as:

Num=2

Echo "this is the $numnd"

This does not print out "this is the 2nd", but only "this is the", because shell searches for the value of the variable numnd, but this variable has no value. You can use curly braces to tell shell that we are printing the num variable:

Num=2

Echo "this is the ${num} nd"

This will print: this is the 2nd

4 Environmental variables

Variables that have been processed by the export keyword are called environment variables. We don't discuss environment variables because they are usually only used in login scripts.

5 Shell command and flow control

There are three types of commands that can be used in shell scripts:

1) Unix command:

Although arbitrary unix commands can be used in shell scripts, there are still some relatively more commonly used commands. These commands are usually used for file and text manipulation.

Common command syntax and functions

Echo "some text": print text on the screen

Ls: file list

Wc-l file wc-w file wc-c file: count the number of lines in the file; count the words in the file; calculate the number of characters in the file

Cp sourcefile destfile: file copy

Mv oldname newname: renaming or moving files

Rm file: deleting fil

Grep 'pattern' file: search for strings such as grep' searchstring' file.txt within a file

Cut-b colnum file: specify the range of file contents to be displayed and output them to a standard output device such as: output the 5th to 9th characters per line cut-b5-9 file.txt should never be confused with the cat command

These are two completely different orders.

Cat file.txt: output file contents to standard output device (screen)

File somefile: get the file type

Read var: prompts the user for input and assigns input to variables

Sort file.txt: sorting lines in the file.txt file

Uniq: delete duplicate lines in the text file, such as: sort file.txt | uniq

Expr: do mathematical operations Example: add 2 and 3 is expr 2 "+" 3

Find: search for files such as: search find by file name. -name filename-print

Tee: output data to standard output devices (screens) and files such as: somecommand | tee outfile

Basename file: returns a file name that does not contain a path, for example: basename / bin/tux will return tux

Dirname file: returns the path where the file resides, for example: dirname / bin/tux will return / bin

Head file: print the first few lines of a text file

Tail file: the last few lines of a printed text file

Sed: Sed is a basic find and replace program. You can read text from standard input, such as command pipes, and set the

The result is output to standard output (screen). This command uses a regular expression (see reference) to search. Don't be confused with wildcards in shell. For example, replace linuxfocus with LinuxFocus: cat text.file | sed's sed's Universe LinuxfocusUniplex LinuxFocusUniver'> newtext.file

Awk: awk is used to extract fields from a text file. By default, the field delimiter is a space, and you can use-F to specify another separator.

Cat file.txt | awk-F,'{print $1 "," $3}'we use here as a field separator to print the first and third fields at the same time. If the contents of the file are as follows: Adam Bor, 34, IndiaKerryMiller, 22, USA command output is: Adam Bor, IndiaKerryMiller, USA

2) Concepts: piping, redirection and backtick

These are not system commands, but they are really important.

The pipe (|) takes the output of one command as the input of another.

Grep "hello" file.txt | wc-l

Search for rows that contain "hello" in file.txt and count them.

Here the output of the grep command is used as the input of the wc command. Of course, you can use multiple commands.

Redirect: outputs the results of the command to a file instead of standard output (screen).

Write to the file and overwrite the old file

> > append to the end of the file to retain the contents of the old file.

Reverse short slash

Use the backslash to use the output of one command as a command-line argument to another.

Command:

Find. -mtime-1-type f-print

Used to find files that have been modified in the past 24 hours (- mtime-2 means the last 48 hours). If you want to package all the files you find, you can use the following linux script:

#! / bin/sh

# The ticks are backticks (`) not normal quotes ('):

Tar-zcvf lastmod.tar.gz `find. -mtime-1-type f-print`

3) process control

1.if

The "if" expression executes the following part of the then if the condition is true:

If... ; then

... .

Elif... ; then

... .

Else

... .

Fi

In most cases, you can use test commands to test conditions. For example, you can compare strings, determine whether the file exists and whether it is readable and so on.

Conditional tests are usually referred to as "[]". Notice that the spaces here are very important. Make sure the square brackets are blank.

[- f "somefile"]: determine whether it is a file or not

[- x "/ bin/ls"]: determine whether / bin/ls exists and has executable permission

[- n "$var"]: determine whether the $var variable has a value

["$a" = "$b"]: judge whether $an and $b are equal

Execute man test to see the types that all test expressions can compare and judge.

Execute the following script directly:

#! / bin/sh

If ["$SHELL" = "/ bin/bash"]; then

Echo "your login shell is the bash (bourne again shell)"

Else

Echo "your login shell is not bash but $SHELL"

Fi

The variable $SHELL contains the name of the login shell, which we compared with / bin/bash.

Shortcut operator

Friends who are familiar with the C language may like the following expression:

[- f "/ etc/shadow"] & & echo "This computer uses shadow passwors"

Here & & is a shortcut operator that executes the statement on the right if the expression on the left is true.

You can also think of it as the and operation in logical operations. The example above indicates that "This computer uses shadow passwors" is printed if the / etc/shadow file exists. The same or operation (| |) is also available in shell programming. Here's an example:

#! / bin/sh

Mailfolder=/var/spool/mail/james

[- r "$mailfolder"]'{echo "Can not read $mailfolder"; exit 1;}

Echo "$mailfolder has mail from:"

Grep "^ From" $mailfolder

The script first determines whether the mailfolder is readable. Print the line "From" in the file if it is readable. If it is not readable or the operation takes effect, the script exits after the error message is printed. There is a problem here, that is, we must have two orders:

◆ print error message

◆ exit program

We use curly braces to put the two commands together as a single command in the form of anonymous functions. General functions are mentioned below.

We can do anything with if expressions without the and / OR operator, but it's much more convenient to use the and / OR operator.

This is the end of the method of executing .sh files in linux. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report