Getting started with Shell Common commands

Source: Internet
Author: User

Getting started with Shell Common commands

This is a series of shell tutorials, including entry, command, and practice.

In this tutorial, we try to minimize the complexity of text descriptions. However, we strive for perfection and focus on instances. The goal is to help readers get started with shell quickly.

The following is the first part of this tutorial, "getting started". You are welcome to make some suggestions and find bugs. We will modify and supplement the suggestions later.

The directory display symbol generated by the CSDN Markdown has a small problem. Refer to the title in the detailed content.

  • Entry
    • First, HelloWorld
      • Echo method 1
    • Second move judgment
      • First, if
        • Judgment Principle
      • The second formula is test and
        • File Test
        • String comparison
        • Integer comparison
      • Third step
    • Third move cycle
      • First
      • Type 2 whileuntil
    • Fourth variable
      • First integer
        • Integer Operation
      • Second string
        • Replace
        • Substring Truncation
        • Wildcard Deletion
      • Third Array
        • Normal Array
        • Join Array
      • Fourth, save the command execution result to the variable
        • And
        • Line feed processing
    • Fifth move redirection
      • Standard input stream standard output stream standard error stream
      • Redirect method list
      • First, stdout is redirected to the standard output stream.
      • Second, redirect the standard error stream stderr
      • Method 3: stdin
    • Sixth recruitment Channel
      • Basic functions of the first pipeline
      • The second pipeline and whileread combination
      • Third-party pipeline and xargs combination
    • 7. wildcard
      • Principle of shell wildcard
      • Wildcard list
      • First step
      • Second step
      • Third step
      • Fourth

 

Shell programming

Replace Linux Shell Parameters

Shell for parameters

Pass Linux/Unix Shell parameters to SQL scripts

Introduction to parameter passing methods in Shell scripts

PASS command line parameters through Shell scripts

Linux Shell wildcards, escape characters, metacharacters, and special characters

Step 1 HelloWorld Step 1: echo
echo "Hello World"
Echo-n "Hello World" # Without line breaks
Echo-e '\ e [0; 33; 1mHello \ e [0 m World' # echo-e '\ e [0; 33; 4mHello \ e [0 m World '# echo-e' \ e [0; 33; 5mHello \ e [0 m World '# color + blinking

Format:\ E [background color; foreground color; highlighted format m, Please read the detailed documentation and use the correct posture for force installation.

Second, Judge first: if
if truethen    echo "Hello World"else    echo "Bug"fiif falsethen    echo "Hello World"elif truethen    echo "Bug"else    echo "Bee"fi
Judgment Principle

if,elifWill execute the command followed by it and check whether the returned value is0, If0Then runthenThe following statement block. Otherwise, the statement is executed.elseThe following statement block.

[bkjia@Ubuntu:~]$ true[bkjia@ubuntu:~]$ echo $?0[bkjia@ubuntu:~]$ false[bkjia@ubuntu:~]$ echo $?1

Note:

  1. true,falseIn fact, it is also a command,trueThe return code of must be0,falseThe return code of must be1
  2. $?IsshellBuilt-in variables used to store the return code of the previous command
Formula 2: test, [], and [[]

test,[ ],[[ ]]Actually allshellAfter the command is executed1Or0And these commands andifThe combination can achieve many judgment functions we need. For example, we can test whether a string is null or not:

s=""if [ -z ${s} ]then    echo "empty"fiif [[ -z ${s} ]]then    echo "empty"fiif test -z ${s}then    echo "empty"fi

In fact,ifAfter[ ],[[ ]],testAll commands can be executed independently.ifWhich branch will be executed later?[ ],[[ ]],testThe returned values are determined. The following is the effect of executing them separately:

[bkjia@ubuntu:~]$ s=""[bkjia@ubuntu:~]$ [ -z "${s}" ][bkjia@ubuntu:~]$ echo $?0[bkjia@ubuntu:~]$ s="abc"[bkjia@ubuntu:~]$ test -z "${s}"[bkjia@ubuntu:~]$ echo $?1[bkjia@ubuntu:~]$ s="123"[bkjia@ubuntu:~]$ [[ 100 -lt ${s} ]][bkjia@ubuntu:~]$ echo $?0

Performance[ ]AndtestThe performance is basically the same,[[ ]]The performance is the highest, the first two5Times (-dOperator testing), so we recommend that you use[[ ]]Improve script performance.

File Test
Operator Description Example
-E filename True if filename exists [-E/var/log/syslog]
-D filename True if filename is a directory [-D/tmp/mydir]
-F filename True if filename is a regular file [-F/usr/bin/grep]
-L filename If filename is a symbolic link, it is true. [-L/usr/bin/grep]
-R filename True if filename is readable [-R/var/log/syslog]
-W filename True if filename is writable [-W/var/mytmp.txt]
-X filename True if filename is executable [-L/usr/bin/grep]
Filename1-nt filename2 If filename1 is newer than filename2, it is true. [/Tmp/install/etc/services-nt/etc/services]
Filename1-ot filename2 If filename1 is earlier than filename2, it is true. [/Boot/bzImage-ot arch/i386/boot/bzImage]
String comparison
Operator Description Example
-Z string If the string length is zero, it is true. [ -z "${myvar}" ]
-N string True if the string length is not zero [ -n "${myvar}" ]
String1 = string2 If string1 is the same as string2, it is true. [ "${myvar}" = "abc" ]
String1! = String2 If string1 is different from string2 [ "${myvar}" != "abc" ]
String1 <string If string1 is smaller than string2, it is true. [ "${myvar}" \< "abc" ]
[[ "${myvar}" < "abc" ]]
String1> string If string1 is greater than string2, it is true. [ "${myvar}" \> "abc" ]
[[ "${myvar}" > "abc" ]]

Note:

  1. Add "" on both sides of the string to prevent errors
  2. <And>It is a string comparison. Do not use an integer for comparison.
  3. If[ ]Used in<And>, You need to write them\<And\>
Integer comparison
Operator Description Example
Num1-eq num2 Equal [3-eq $ mynum]
Num1-ne num2 Not equal [3-ne $ mynum]
Num1-lt num2 Less [3-lt $ mynum]
Num1-le num2 Less than or equal [3-le $ mynum]
Num1-ge num2 Greater than or equal [3-ge $ mynum]
Method 3: &, |
&&It can be used to evaluate the sum of the two judgment statements
if [ -n "abc" ] && [ -n "aa" ]
if [[ -n "abc" ]] && [[ -n "aa" ]]
if test -n "abc" && test -n "aa"
if [[ -n "abc" && -n "aa" ]]

Note: Only[[ ]]To allow&&Written in

||It can be used to evaluate or
if [ -n "abc" ] || [ -n "aa" ]
if [[ -n "abc" ]] || [[ -n "aa" ]]
if test -n "abc" || test -n "aa"
if [[ -n "abc" || -n "aa" ]]

Tips

&&,||It can also be used to concatenate commands to determine whether to execute the last command based on whether the previous command is successful or not.

Cd/data & ls # When 'CD/data' returns 0 (SUCCESS) when the 'LS' cd/data | cd/root # When 'CD/data' returns non-0 (that is, failure), The 'CD/root'
Step 3: loop first:
for i in {1..100}do    echo ${i}done

Note:

  1. {1..100}Is a wildcard method.1 2 3 ... 100(1 ~ 100 separated by spaces.

  2. For examplefor i in 1 2 3;Such a statement,forWill1,2,3Values are assignediAnd for the configuration,forThe wildcard is expanded, and each item in the wildcard is assignedi.

for i in `seq 100`do    echo ${i}donefor i in `seq 1 2 100`do    echo ${i}done

Note:

  1. seqItself is a command used to output a sequence composed of numbers, suchseq 100Will generate and Output1 2 3 ... 100(1 ~ 100 separated by line breaks ).seq 1 2 100Will generate and Output1 3 5 ... 99(Values starting from 1 and 2 are equal to less than 100 in the series with tolerances, which are separated by linefeeds ).
  2. The command between the backquotes (') is executed, and the output result is converted into a variable.for inWill be retrieved in sequenceseqThe execution result is assignedi.
for ((i = 0; i < 100; i++))do    echo ${i}donefor ((i = 0; i < 100; i+= 2))do    echo ${i}done

Note:

The above is in the C language formatforThe loop syntax is basically the same. The difference lies in the double brackets:(( ))

Formula 2: while and
i=0while [[ ${i} -lt 100 ]]do    echo ${i}    ((i++))done
i=0until [[ ${i} -ge 100 ]]do    echo ${i}    ((i++))done

Note:

whileAnduntilPrinciples andifIs similar, it will execute and it follows the command, the difference is:

  • whileYesthe return value of the following statement is0, The statement block in the execution loop. Otherwise, the loop jumps out;
  • untilThe Return Value of the subsequent statement is not0.

For more details, please continue to read the highlights on the next page:

  • 1
  • 2
  • 3
  • Next Page

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.