Shell Scripting Learning

Source: Internet
Author: User

What is a shell script?

A shell script is a text file that contains one or more commands.

As a system administrator, we often need to use multiple commands to accomplish a task, and we can add these commands in a text file (shell script) to accomplish these everyday tasks.


What is the default login shell and how to change the login shell for a specified user

On the Linux operating system, "/bin/bash" is the default login shell, which is assigned when the user is created. Use the CHSH command to change the default shell

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/82/C2/wKiom1df-g7CsjO3AAAbWQ0IGJA606.png "title=" Shell Changed. PNG "alt=" Wkiom1df-g7csjo3aaabwq0igja606.png "/>


What types of variables can be used in shell scripts

Two types of variables:

System-defined variables

User-defined variables

"Set" command or echo $ variable name to view variable values


Special variables

In the test.sh file

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/82/C2/wKiom1dgCaGhGwo0AAAZGLtj_xo609.png "title=" 13.PNG "alt=" Wkiom1dgcaghgwo0aaazgltj_xo609.png "/>

Operation Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/82/C1/wKioL1dgComQbQxhAAA1Vn6Iipk109.png "title=" 12.PNG "alt=" Wkiol1dgcomqbqxhaaa1vn6iipk109.png "/>


“#! The role of/bin/bash "

This is the first line of the shell script to become (shebang) line, here # called hash,! called Bang

It means that the order is executed by/bin/bash.


How to make a script executable

chmod u+x test.sh


How to add comments

Comments start with #


How to cancel a variable or variable assignment

unset variable Name


How to let the shell get input from the terminal on the script

The read command gets the user's input and is placed in the variable you gave


If

if [Condition];then

Command 1

Command 2

...

elif [Conditional];then

Command 1

Command 2

...

Else

if [Condition];then

Command 1

Command 2

...

Else

Command 1

Command 2

...

Fi

Fi

Test.sh:

printf  "please enter your name: " read nameprintf  "Please Enter  your score:  "                                                read score #[[   $score  -lt 90 ]] | |  {[  $score  -lt 90 ] | |  {    echo  "Hi, $name, you are very good!"}  if [  $score  -ge 90 ];then    echo  "hi ${name},you  are very good! " elif [  $score  -ge 80 -a  $score  -lt 90 ];then     echo  "hi  $name, you are good!" elif [  $score  -ge 60 -a  $score  -lt 80 ];then    echo  "hi  $name, you are normal!" else    echo  "Who are you??" Fi

Operation Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/82/C2/wKiom1dgD-KxVG8NAAB8Rx0_50g679.png "title=" 16.PNG "alt=" Wkiom1dgd-kxvg8naab8rx0_50g679.png "/>


For

For variable in loop list

Do

Command 1

Command 2

...

Done

Test.sh:

For I in {A.. Z}do if [-b/dev/sd${i}];then EC Ho "Yes!,disk id/dev/sd${i}" fi done

Operation Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/82/C2/wKiom1dgEH3SZSWYAAAO3y2ZqHk099.png "title=" 17.PNG "alt=" Wkiom1dgeh3szswyaaao3y2zqhk099.png "/>

Test.sh:

Sum=0 for I in {1..100}do let Sum+=idoneecho "$sum"

Operation Result:

5050

Test.sh:

Sum=0 for ((i=0; i<=100; i++)) does let sum +=idoneecho $sum

Operation Result:

5050


While

while [condition]

Do

Command

Done

Test.sh:

While [$#-GT 0] do echo shift 1done

Operation Result:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/82/C3/wKiom1dgE2bTT3vwAAAXPmvNp3s379.png "title=" 20.PNG "alt=" Wkiom1dge2btt3vwaaaxpmvnp3s379.png "/>


Do-while

Do

{

Command

}while (condition)


Case

Case variable in

Value 1)

Command

;;

Value 2)

Command

;;

*)

Command

;;

Esac

Test.sh:

    case  "$"  in    start | -s | -s  )                                                                       echo  "Your cmd  is start "        ;;       st[oO]p )         echo  " Your cmd is stop "        ;;       restart )         echo  " Your cmd is restart "        ;;       * )          echo  "your  cmd is default "        ;;   esac

Operation Result:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/82/C2/wKiom1dgERLywbpGAAAxeeMoEno499.png "title=" 18.PNG "alt=" Wkiom1dgerlywbpgaaaxeemoeno499.png "/>


Until

Test.sh:

I=0sum=0until [$i-gt]do let sum+=i let i++ doneecho $sum

Operation Result:

5050


"$?" in the shell script What is the purpose of the tag?

When writing a shell script, if you want to check whether the previous command executed successfully, "$?" Can be used to check the end state of the previous command, 0 for success


How to compare two numbers in a shell script

Use test or [test, such as:

#! /bin/bashx=10y=20if [x-gt y];then echo "x > Y" else echo "y <= X" fi


How to compare two strings in a shell script

Test.sh:

str= "Hello World" ["x$str" = = "Xhello World"-o "x$str" = = "Xhello World"]echo $? ["x$str" = = "Xhello World"-a-f "test.sh"-a-d "dir"-A! "Xstr" = = "Xhello bit"]echo $?

Results:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/82/C1/wKioL1dgECHz4x1uAAAM6AmTcjk647.png "title=" 15.PNG "alt=" Wkiol1dgechz4x1uaaam6amtcjk647.png "/>

Test.sh:

Read STR ["x$str" = = "X"]echo $? [-Z] $str "]echo $? [!-Z "$STR"]echo $? [-N "$str"]echo $?                                                                                [!-n "$str"]echo $? [ ! "X$STR"! = "Xhello"]echo $?

Results:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/82/C1/wKioL1dgDxDjtCX4AAAh-lOBXbM473.png "title=" 14.PNG "alt=" Wkiol1dgdxdjtcx4aaah-lobxbm473.png "/>


In the shell script, how to test the file

Test command or [command, for example:


650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/82/C0/wKioL1dgA0Xyhv4HAAAVXIu8NVA177.png "title=" 9.PNG " alt= "Wkiol1dga0xyhv4haaavxiu8nva177.png"/>

[-D file name]

[-D "$STR"]

Where-d means that if the file exists and is a directory, return True, of course, it can be another option, more than-D

-E means that if the file exists, returns true

-F means that if the file exists and is a normal file, returns True

-R means that if the file exists and is readable, returns true

-S means that if the file exists and is not empty, returns true

-W indicates that if the file exists and is writable, returns true

-X means that if the file exists and is executable, returns true


How to perform arithmetic operations

Two methods:

1. Using the expr command

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/82/C0/wKioL1dgB33TU_5xAAAx9CT0qCw004.png "title=" 11.PNG "alt=" Wkiol1dgb33tu_5xaaax9ct0qcw004.png "/>

2, $[expression], such as:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/82/C0/wKioL1dgByWj-Ns8AAAWdn2M9SA058.png "title=" 10.PNG "alt=" Wkiol1dgbywj-ns8aaawdn2m9sa058.png "/>



How to redirect standard output and error output to the same location

1, such as Ls/usr/share/doc > OUT.txt 2>&1

2, such as Ls/usr/share/doc &> OUT.txt


How to define a function in a shell script

A function is a block of code that has a name. When we define the code block, we can invoke the function name in our script and the code block will be executed.

Function name () {

Command

return 0

}


Some psychic powers of ${}

Define a variable:

File=dir1/dir2/dir3/my.file.txt

You can use ${} to replace each other to get different values:

${file#*/} take out the first/its left string: dir1/dir2/dir3/my.file.txt

${file##*/} take out the last/and left string: my.file.txt

${file#*.} Take out the first one. And the string to the left: file.txt

${file##*.} Take off the last one. And the string to the left: txt

${file%/*} take out the last/And right string:/dir1/dir2/dir3

${file%%/*} take out the first/and the right string: (null value)

${file%.*} take off the last one. And the string to the right:/dir1/dir2/dir3/my.file

${file%%.*} take off the first one. And the string to the right:/dir1/dir2/dir3/my

Test.sh:

File=dir1/dir2/dir3/my.file.txt echo ${file#*/}echo ${file##*/}echo ${file#*. Echo ${file##*.} echo ${file%/*}echo ${file%%/*}echo ${file%.*}echo ${file%%.*} echo ${file:0:4}echo ${file:4:5} Echo ${file/dir/path} Echo ${file//dir/path} echo ${#file}

Operation Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/82/C1/wKioL1dgE3HjmGgUAAA_5PJ47e0865.png "title=" 19.PNG "alt=" Wkiol1dge3hjmgguaaa_5pj47e0865.png "/>


How to debug a shell script

1. Use the '-X ' parameter (bash-x test.sh)

2. Use '-nv ' parameter (BASH-NV test.sh)


Here are three pieces of code

1.

Cd..

Ls


2.

Var=45

echo $ (($VAR/3))

echo $ ((16#2A))


3.

Data= ' Date '

Echo ${data}

Echo $DATA

data=$ (date)

Echo $DATA

echo the last Sunday was $ (date-d "last Sunday" +%y-%m-%d)



Finish

This article is from the "Zero Egg" blog, please be sure to keep this source http://lingdandan.blog.51cto.com/10697032/1789336

Shell Scripting Learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.