preface

Christmas is here! Eqijun here wish all fans a merry Christmas! I wish you all the postgraduate entrance examination students gold list title! I wish the friend who is looking for a job receive offer explosion! I wish you all a happy New Year!

Here you specially use shell script to draw a Christmas tree! Let’s take a look at the execution results first!

So how do you create this special Christmas tree? Below a gentleman hand to teach everyone! Those of you who just want to run scripts can go to the back!

1. Shell script knowledge

1. Shell variables

Variables are an essential part of any programming language and are used to store all kinds of data. Scripting languages usually define variables without specifying the type, and assign values directly. Shell variables follow this rule as well. The Shell supports three ways to define variables:

variable=value
variable='value'
variable="value"
Copy the code

Variable is the name of the variable, and value is the value assigned to the variable. If the value does not contain any whitespace (such as Spaces, Tab indents, and so on), you can omit quotation marks. If the value contains whitespace, it must be enclosed in quotation marks. There is also a difference between using single quotes and double quotes, which we’ll explain later.

Note that there can be no Spaces around the assignment sign =, which is probably different from most programming languages you’re familiar with.

The naming conventions for Shell variables are the same as in most programming languages:

  • The variable name consists of numbers, letters, and underscores.
  • Must start with a letter or underscore.
  • Keywords in the Shell cannot be used (reserved keywords can be viewed using the help command).

Use the variable

To use a defined variable, just prefix the variable name with the dollar sign $, as in:

skill="C, Linux"
echo "I am good at ${skill}Script"
Copy the code

The curly braces {} around the variable name are optional, with or without them, to help the interpreter recognize the bounds of the variable. If you leave the skill variable out of curly braces and write echo “I am good at $skillScript”, the interpreter will treat $skillScript as a variable (with a null value) and the code will not perform as expected.

Modifies the value of a variable

lin=2
let lin++
Copy the code

The difference between single and double quotation marks

When you define a variable, the value of a variable can be enclosed by either a single quote “” or a double quote” “. What’s the difference? Consider the following code as an example:

#! /bin/bash
name="A bite of Linux"
gzh1=${name}'
gzh2="C Language Chinese website:${name}"
echo $gzh1
echo $gzh2
Copy the code

Running results:

The public no. :${name}Official number: a mouthful of LinuxCopy the code

Enclosing the value of a variable in single quotation marks will output whatever is inside the single quotation marks, even if variables and commands are contained in the content (commands need to be raised backwards). This is a good way to define scenarios that display pure strings, that is, scenarios where you don’t want to parse variables, commands, and so on.

When a variable value is enclosed in double quotation marks (” “), the variable name and command inside the variable are parsed first, rather than the variable name and command inside the double quotation marks. This works best for variable definitions with variables and commands attached to a string that you want to parse before printing.

Suggestion: If the variable content is a number, do not use quotation marks. Single quotes are used if you really want the original output; It is best to use double quotation marks for other strings that do not have special requirements. Double quotation marks are the most common scenario when defining variables.

2. trap

The trap command is dedicated to capturing signals. For example, CTRL + C sends interrupt signals to terminals and so on. After the signal is captured, a series of actions can be performed.

Usage:

trap  'COMMAND' INT     
Copy the code

COMMAND indicates the action to be performed by the trap COMMAND after it receives an INT signal.

Signals that can be captured include: HUP INT Signals that are not applicable to capture: KILL TERM

Signal response mode

Once a trap has caught a signal, it can respond in three ways:

  • 1. Execute a procedure to process the signal
  • 2. Accept the default operation of the signal
  • Ignore the signal

It comes in three forms that correspond to three different ways of responding to signals:

trap ""commands"" signal-list
Copy the code

When the script receives a signal listed in the signal-list listing, the trap command executes the command in the double quotes.

The second:

trap signal-list
Copy the code

Trap does not specify any command and accepts the default action of the signal. The default action is to end the process. The third:

trap "" "" signal-list
Copy the code

The trap command specifies an empty command string that allows signals to be ignored.

You can run the trap -l command to view the signals:

# trap -l1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14  49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAXCopy the code

3. clear

Clear terminal screen

4. tput

The tput command initializes and manipulates your terminal session through the Terminfo database. Using tPUT, you can change several terminal functions, such as moving or changing the cursor, changing text properties, and clearing specific areas of the terminal screen.

The cursor attributes

tput sc          ## Record cursor position
tput cup x y     ### Move the cursor to column X and row Y
tput rc          ## Returns the cursor position
tput civis       ## Hide cursor
tput cnorm       ## Display cursor
tput setaf ColorNumber ## Set the foreground color
tput setab ColorNumber ## Set the background color
tput clear      # Clear screen
tput cup x y    The cursor moves according to the set coordinate point
Copy the code

Text attributes

tput blink      # Text flicker
tput bold       # Bold text
tput el         Clear to end of line
tput smso       Enable Highlight mode
tput rmso       # Stop highlighting mode
tput smul       # underline mode
tput rmul       # Ununderline mode
tput sgr0       Restore the default terminal
tput rev        # Inverting terminal
Copy the code

In addition, you can change the color of the text

Tput setB Color code tPUT setf Color codeCopy the code

For example,

# bold
bold=$(tput bold)
# the underline
underline=$(tput sgr 0 1)
# reset rule
reset=$(tput sgr0)
# red
red=$(tput setaf 1)
# green
green=$(tput setaf 2)
Copy the code

Below is a clock with flicker function

#! /bin/bash

for((i=0; i<8; i++))do
        tput sc; tput civis                     Record cursor position and hide cursor
        tput blink; tput setf $i                # Text flicker, change the text color
        echo -ne $(date +'%Y-%m-%d %H:%M:%S')   # display time
        sleep 1
        tput rc                                 Restore cursor to record position
done

tput el; tput cnorm                             Clean up terminal and restore cursor display
Copy the code

The effect

5. The for loop

The for loop works by fetching elements sequentially, placing them in a specified variable, and then repeating the enclosed command area (between do and done) until all elements are fetched.

Where serial is a combination of strings separated from each other by separators (such as Spaces) defined by $IFS, called fields.

The syntax structure for is as follows:

1. forvariableinSerial port 2.do3. Run command 4.done
Copy the code

Description:

Line 1 iterates the fields in the serial into lines 2-4 of the variable, and then repeats the command area between do and done until every field in the serial has been processed.

For example, use the for loop to create aaA1-AAa10 in the home directory, and then create the bbb1-bbb10 directory in aaA1-aaa10

1. #! /bin/bash
2. for k in $( seq 1 10 )
3. do
4.    mkdir /home/peng/aaa${k}
5.    cd /home/peng/aaa${k}
6.    for l in $( seq 1 10 )
7.    do
8.    mkdir bbb${l}
9.    cd /home/peng/aaa${k}
10.   done
11.   cd.done
Copy the code

Lists the disk space occupied by each subdirectory in the var directory.

#! /bin/bash
DIR="/var"
cd $DIR
for k in $(ls $DIR)
do
  [ -d $k ] && du -sh $k
done
Copy the code

6. The while loop

Syntax for the while loop:

1. whileCondition test 2.do3. Run command 4.done
Copy the code

Description:

Line 1, first condition test, if the return value is 0 (condition test is true), enter the loop, execute the command area, otherwise do not enter the loop, introductionwhileCommand line 3, execution command area, these commands should have the command to change the conditional test, so that there is a chance to end execution after a limited number of stepswhileLoops (unless you want to execute an infinite loop). Line 4, go back to line 1, executewhileThe commandCopy the code

Flow chart:Example calculation 1+2+3………… 10

#! /bin/bash
declare -i i=1
declare -i sum=0
while ((i<=10))
do
  let sum+=i
  let ++i
done
echo $sum
Copy the code

Second, the Christmas tree script file

#! /bin/bash
# Write a Christmas tree with shell
# created at 2021-12-23
trap "tput reset; tput cnorm; exit" 2
clear
tput civis
lin=2
col=$(($(tput cols) / 2))
c=$((col-1))
est=$((c-2))
color=0
tput setaf 2; tput bold

# Print leaves
for ((i=1; i<20; i+=2))
{
    tput cup $lin $col
    for ((j=1; j<=i; j++))
    {
        echo -n \*
    }
    let lin++
    let col--
}

tput sgr0; tput setaf 3

# Print tree trunk
for ((i=1; i<=2; i++))
{
    tput cup $((lin++)) $c
    echo '| |'
}
new_year=$(date +'%Y')
let new_year++
tput setaf 222; tput bold
tput cup $lin $((c - 10));  echo $new_yearMerry Christmas!! color=122 tput setaf$color; tput bold
tput cup $((lin + 1)) $((c - 10)); echoConcern public number: a mouthful Linux!let c++
k=1

# Decorate
while true; do
    for ((i=1; i<=35; i++)) {
        # Turn off the lights
        [ $k -gt 1 ] && {
            tput setaf 2; tput bold
            tput cup ${line[$[k-1]$i]} ${column[$[k-1]$i]}; echoA \ *unset line[$[k-1]$i]; unset column[$[k-1]$i] 
        }

        li=$((RANDOM % 9 + 3))
        start=$((c-li+2))
        co=$((RANDOM % (li-2) * 2 + 1 + start))
        tput setaf $color; tput bold
        tput cup $li $co
        echo o
        line[$k$i] =$li
        column[$k$i] =$co
        color=$(((color+1) %8))
       
        sh=1
		#for l in M O N E Y
		for l inA mouthful of Li nu x!do
            tput cup $((lin+1)) $((c+sh))
            echo $l
            let sh++
            letSh++ sleep 0.02done
    }
    k=$((k % 2 + 1))
done
Copy the code

Execute the script

root@ubuntu:/home/peng/work/test# chmod 777 peng.sh
root@ubuntu:/home/peng/work/test# ./peng.sh 
Copy the code

What are you waiting for? Hurry up and run!