shellecho, printf, test command and shell process control

1, echo command

Echo instruction is used for string output. Command format: echo string

1. Display normal string: echo "It is a test" or echo It is a test result: It is a test

2. Escape characters can also be displayed: echo "\"It is a test \ "" the result will be "It is a test"

3. Display variables:

The read command reads a line from standard input and assigns the value of each field of the input line to a shell variable

#!/bin/sh
read name 
echo "$name It is a test"

Save the above code as test SH, name receives the standard input variable, and the result will be:

[root@www ~]# sh test.sh
 OK # standard input
 OK It is a test # output

4. Show wrap

echo -e "OK! \n" # -e enable escape
echo "It is a test"

Output result:

OK!

It is a test

5. Show no line breaks

#!/bin/sh
 echo -e "OK! \c" # -e enable escape \ c do not wrap
echo "It is a test"

Output result:

OK! It is a test

6. Input the display results into a file

echo "It is a test" > myfile

(> symbol will overwrite the old contents of the file, and > > symbol means append to the end of the file)

7. Output the string as it is without escaping or taking variables (use single quotation marks)

echo '$name\"'

Output result:

$name\"

8. Display execution results

echo `date`

Note: the back quotation mark `, not the single quotation mark ', is used here.

The result shows the current date

Thu Jul 24 10:08:46 CST 2014

2, printf command

The printf command mimics the printf() program in the C library.

Printf is defined by the POSIX standard, so scripts using printf are more portable than using echo.

Printf uses parameters separated by reference text or spaces. Outside, you can use formatted strings in printf. You can also specify the width and left-right alignment of strings. The default printf will not automatically add line breaks like echo. We can add them manually. \ n.

Syntax of printf command:

printf  format-string  [arguments...]

Parameter Description:

  • Format string: format control string
  • arguments: is a parameter list.

example

$ echo "Hello, Shell"
Hello, Shell
$ printf "Hello, Shell\n"
Hello, Shell
$

Next, I'll use a script to reflect the powerful function of printf:

example

#!/bin/bash
# author: rookie tutorial
# url:www.runoob.com
 
printf "%-10s %-8s %-4s\n" Name Gender weight kg  
printf "%-10s %-8s %-4.2f\n" Guo Jingnan 66.1234
printf "%-10s %-8s %-4.2f\n" Guo Nan Yang 48.6543
printf "%-10s %-8s %-4.2f\n" Guo funu 47.9876

Execute the script, and the output results are as follows:

Name Gender weight kg
 Guo Jing, male, 66.12
 Yang Guo, male 48.65
 Guo Fu female 47.99

%S% c% d% f , are all format substitutes,% s , outputs a string,% d , integer output,% c , outputs a character,% f , outputs a real number and outputs it in decimal form.

%-10s - refers to a character with a width of 10 characters (- indicates left alignment and no indicates right alignment). Any character will be displayed in the character with a width of 10 characters. If it is insufficient, it will be automatically filled with spaces, and if it exceeds, all the contents will be displayed.

%-4.2f , refers to formatting as decimal, where. 2 , refers to retaining 2 decimal places.

 

example

#!/bin/bash
# author: rookie tutorial
# url:www.runoob.com
 
# Format string is a double quotation mark
printf "%d %s\n" 1 "abc"

# Single quotation marks have the same effect as double quotation marks
printf '%d %s\n' 1 "abc"

# You can output without quotation marks
printf %s abcdef

# The format specifies only one parameter, but the extra parameters will still be output according to the format, and the format string will be reused
printf %s abc def

printf "%s\n" abc def

printf "%s %s %s\n" a b c d e f g h i j

# If there are no arguments, then% s is replaced by NULL and% d is replaced by 0
printf "%s and %d \n"

Execute the script, and the output results are as follows:

1 abc
1 abc
abcdefabcdefabc
def
a b c
d e f
g h i
j  
 and 0

Escape sequence of printf

sequenceexplain
\aWarning character, usually ASCII BEL character
\bback off
\cSuppress (do not display) any ending newline character in the output result (valid only in the parameter string controlled by the% b format indicator), and any character left in the parameter, any subsequent parameter and any character left in the format string are ignored
\fForm feed
\nLine feed
\rCarriage return
\tHorizontal tab
\vvertical tab
\\A literal backslash character
\dddA character representing a 1 to 3 digit octal value. Valid only in format strings
\0dddA character representing an octal value of 1 to 3 digits

example

$ printf "a string, no processing:<%s>\n" "A\nB"
a string, no processing:<A\nB>

$ printf "a string, no processing:<%b>\n" "A\nB"
a string, no processing:<A
B>

$ printf "www.runoob.com \a"
www.runoob.com $                  #nowrap 

3, test command

The test command in the Shell is used to check whether a condition is true. It can test values, characters and files.

1. Numerical test

parameterexplain
-eqEqual to true
-neNot equal to true
-gtGreater than is true
-geGreater than or equal to is true
-ltLess than is true
-leTrue if less than or equal to

example:

num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

Output result:

The two numbers are equal!

[] in the code performs basic arithmetic operations, such as:

#!/bin/bash

a=5
b=6

result=$[a+b] # Note that there should be no spaces on either side of the equal sign
echo "result For: $result"

The result is:

The result is: 11

2. String test

parameterexplain
=Equal to true
!=True if not equal
-z stringIf the length of the string is zero, it is true
-n stringTrue if the length of the string is not zero

example:

num1="ru1noob"
num2="runoob"
if test $num1 = $num2
then
    echo 'Two strings are equal!'
else
    echo 'The two strings are not equal!'
fi

Output result:

Two strings are not equal!

3. File test

parameterexplain
-e file nameTrue if the file exists
-r file nameTrue if the file exists and is readable
-w file nameTrue if the file exists and is writable
-x file nameTrue if the file exists and is executable
-s file nameTrue if the file exists and has at least one character
-d file nameTrue if the file exists and is a directory
-f file nameTrue if the file exists and is a normal file
-c file nameTrue if the file exists and is a character type special file
-b file nameTrue if the file exists and is a block special file

example

cd /bin
if test -e ./bash
then
    echo 'file already exist!'
else
    echo 'file does not exist!'
fi

Output result:

File already exists!

In addition, Shell also provides and (- a), or (- o), non (!) Three logical operators are used to connect test conditions, and their priority is:! Highest, - A - followed by, - o - lowest. For example:

example

cd /bin
if test -e ./notFile -o -e ./bash
then
    echo 'At least one file exists!'
else
    echo 'Neither file exists'
fi

Output result:

At least one file exists!

4, Process control of shell (important and common)

1, if

1. In the shell, the format of if is: if # then # fi

(fi, it can be seen that it is the terminator of this process control)

For example:

if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi

Indicates: query the ssh process, - gt 1 indicates that the number of matching threads is greater than 1. At this time, if it is true, execute echo "true"

2. The format used is: if # then # else # fi

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

3. The format of if # else if else is: if # then # elif # then # else # fi

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

example:

a=10
b=20
if [ $a == $b ]
then
   echo "a be equal to b"
elif [ $a -gt $b ]
then
   echo "a greater than b"
elif [ $a -lt $b ]
then
   echo "a less than b"
else
   echo "No conditions met"
fi

Result: a is less than b

if statements are often used together with test (of course, they can often be used directly without test), for example:

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'Two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

Result: the two numbers are equal!

(that is, else if becomes elif, and the code to be executed by each if or elif is written in then (the code of else does not need to be matched with then), and finally ends with fi)

 

2, for loop

The format is as follows:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

in is followed by the list to be cycled (list elements are separated by spaces). Each time the value of a list is obtained, it is assigned to var.

done is the terminator.

For example:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

Output result:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

3, while loop

Syntax format:

while condition
do
    command
done

Example: the following is a basic while loop. The test condition is: if int is less than or equal to 5, the condition returns true. Int starts from 1. In each cycle, int adds 1. Run the above script, return the numbers 1 to 5, and then terminate.

(the let command is used to execute one or more expressions. After the let command, the variable can be calculated without adding $to represent the variable)

#!/bin/bash
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

result:

1
2
3
4
5

At this time, we can use while to read the keyboard information. In the following example, the input information is set to the variable FILM, and press < ctrl-d > to end the cycle.

echo 'Press <CTRL-D> sign out'
echo -n 'Enter the name of your favorite website: '
while read FILM
do
    echo "yes! $FILM It's a good website"
done

result:

Press < ctrl-d > to exit
 Enter your favorite website name: rookie tutorial
 yes! Rookie tutorial is a good website

Infinite loop:

while :
do
    command
done

perhaps

while true
do
    command
done

perhaps
for (( ; ; ))

4, until loop

The until loop executes a series of commands until the condition is true.

until loop and while loop are handled in the opposite way.

while loops are generally better than until loops, but in some cases - and only in rare cases - until loops are more useful.

until syntax format:

until condition
do
    command
done

condition is generally a conditional expression. If the return value is false, continue to execute the statements in the loop body, otherwise jump out of the loop.

In the following example, we use the until command to output numbers from 0 to 9:

example

#!/bin/bash

a=0

until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

Operation results:

The output result is:

0
1
2
3
4
5
6
7
8
9

5, Case esac

That is, multiple selection statements, and switch in java Similar to case, each case minute starts with a right parenthesis and two semicolons;; Indicates a break. esac is the end tag of case multiple selection statement.

Syntax format:

case value in
 Mode 1)
    command1
    command2
    ...
    commandN
    ;;
Mode 2)
    command1
    command2
    ...
    commandN
    ;;
esac

As shown above, the value must be followed by in, where each matching value is successfully matched, start with the right parenthesis, and execute the command until;;

When the first mock exam is matched, a pattern will not be executed. If no match is applied to any one mode, then the mode of * will be executed. For example:

echo 'Enter a number between 1 and 4:'
echo 'The number you entered is:'
read aNum
case $aNum in
    1)  echo 'You chose 1'
    ;;
    2)  echo 'You chose 2'
    ;;
    3)  echo 'You chose 3'
    ;;
    4)  echo 'You chose 4'
    ;;
    *)  echo 'You didn't enter a number between 1 and 4'
    ;;
esac

If you enter different contents, you will have different results, for example:

Enter a number between 1 and 4:
The number you entered is:
3
 You chose 3

Another example:

#!/bin/sh

site="runoob"

case "$site" in
   "runoob") echo "Rookie tutorial"
   ;;
   "google") echo "Google search"
   ;;
   "taobao") echo "TaoBao"
   ;;
esac

result:

Rookie tutorial

6, Jump out of loop

1,break

For example:
 

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5! game over"
            break
        ;;
    esac
done

result:

Enter a number between 1 and 5:3
 The number you entered is 3!
Enter a number between 1 and 5:7
 The number you entered is not between 1 and 5! game over

2,continue

For example:

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5!"
            continue
            echo "game over"
        ;;
    esac
done

Running the code found that when a number greater than 5 is entered, the loop in this example will not end, and the "game end" statement "echo" will never be executed.

aa

Keywords: Operating System

Added by gothica on Fri, 28 Jan 2022 08:57:15 +0200