Merry Christmas. I teach you to use shell script to realize a Christmas tree. [little cool]

Posted by temidayo on Fri, 24 Dec 2021 00:11:23 +0100

preface

Christmas is coming!
Yikoujun is here to wish all fans a merry Christmas!
I wish all the students who take the postgraduate entrance examination a golden title!
I wish my friends who are looking for a job get a hot offer!
I wish all bosses a lot of money in the New Year!

Here, I drew a Christmas tree with a shell script!
Let's take a look at the implementation results first!

So how can we write this special effect Christmas tree?
Next, I'll teach you!
Students who just want to run the script can jump to the back!

1, shell script knowledge

1. shell variables

Variables are an essential part of any programming language. Variables are used to store all kinds of data. Scripting languages usually do not need to specify the type when defining variables. They can assign values directly. Shell variables also follow this rule.
Shell supports the following three ways to define variables:

variable=value
variable='value'
variable="value"

Variable is the variable name and value is the value assigned to the variable. If value does not contain any whitespace characters (such as spaces, Tab indents, etc.), quotation marks may not be used; if value contains whitespace characters, quotation marks must be used. There is also a difference between using single quotation marks and using double quotation marks, which will be explained in detail later.

Note that there should be no spaces around the assignment number =, which may be different from most programming languages you are familiar with.

The naming convention of Shell variables is the same as that of 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 through the help command).

Use variables

A defined variable can be used as long as the dollar sign $is added in front of the variable name, such as:

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

The curly braces {} outside the variable name are optional. They can be added or not. The curly braces are added to help the interpreter identify the boundary of the variable
If you do not add curly braces to the skill variable and write echo "I am good at $skillScript", the interpreter will treat $skillScript as a variable (its value is empty), and the code execution result will not be what we expect.

Modify the value of the variable

lin=2
let lin++

The difference between single quotation marks and double quotation marks

When defining a variable, the value of the variable can be enclosed by single quotation marks' 'or double quotation marks''. What is the difference between them? Take the following code as an example:

#!/bin/bash
name="a bite Linux"
gzh1='Official account: ${name}'
gzh2="C Language Chinese website: ${name}"
echo $gzh1
echo $gzh2

Operation results:

Official account: ${name}
The official account: one mouth Linux

When you enclose the value of a variable with a single quotation mark '', whatever is in the single quotation mark will be output. Even if there are variables and commands in the content (the commands need to be quoted back), they will be output as they are. This method is more suitable for defining and displaying Pure Strings, that is, you do not want to parse variables and commands.

When the value of a variable is enclosed in double quotation marks "", the variables and commands inside will be parsed when outputting, rather than outputting the variable names and commands in double quotation marks as they are. This method is more suitable for variable definitions with variables and commands attached to the string and you want to parse them before outputting them.

Recommendations:
If the content of the variable is a number, you can leave it without quotation marks; If you really need to output as is, add single quotation marks; Other strings without special requirements are best enclosed in double quotation marks. When defining variables, double quotation marks are the most common use scenario.

2. trap

The trap command is dedicated to capturing signals. For example, the interrupt signal sent by ctrl+c to the terminal, etc. After capturing the signal, a series of operations can be carried out.

Usage:

trap  'COMMAND' INT     

COMMAND indicates the action to be performed by the trap COMMAND after receiving the INT signal.

Signals that can be captured include: HUP INT, etc
Signal not applicable to capture: KILL TERM

Signal response mode

After the trap captures the signal, it can respond in three ways:

  • 1. Execute a program to process this signal
  • 2. Accept the default operation of the signal
  • 3. Ignore this signal

It has three forms, corresponding to three different signal response modes
First:

trap ""commands"" signal-list

When the script receives the signal listed in the signal list list, the trap command executes the command in double quotation marks

Second:

trap signal-list

trap does not specify any command and accepts the default operation of the signal The default action is to end the process
Third:

trap "" "" signal-list

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

Use the trap -l command to see which signals are available:

# trap -l
 1) 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) SIGRTMAX

3. clear

Clear terminal screen

4. tput

The tput command initializes and operates 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.

Cursor properties

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

Text properties

tput blink      # Text flashing
tput bold       # Text bold
tput el         # Clear to end of line
tput smso       # Start highlight mode
tput rmso       # Stop highlight mode
tput smul       # Underline mode
tput rmul       # Cancel underline mode
tput sgr0       # Restore default terminal
tput rev        # Inverting terminal

In addition, you can change the color of the text

tput setb Color code 
tput setf Color code 

give an example

#Bold
bold=$(tput bold)
#Underline
underline=$(tput sgr 0 1)
#Rules Reset 
reset=$(tput sgr0)
#gules
red=$(tput setaf 1)
#green
green=$(tput setaf 2)

Here is a clock with flashing function

#!/bin/bash

for ((i=0;i<8;i++))
do
        tput sc; tput civis                     # Record the cursor position and hide the cursor
        tput blink; tput setf $i                # Text blinks to 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                             # When exiting, clean the terminal and restore the cursor display

effect

5. for loop

The operation mode of the for loop is to take out the meaning of serial elements, put them into the specified variables in order, and then repeat the enclosed command area (between do and done) until all elements are taken.

Among them, serial is a combination of strings separated by separators (such as space characters) defined by $IFS. These strings are called fields.

The syntax structure of for is as follows:

1. for variable in serial 
2. do
3.    Execute command
4. done

explain:

Line 1: put the field iteration in the serial into the variable
Line 2-4, and then the command area between do and done will be repeated until each field in the serial has been processed.

give an 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

List the disk space occupied by each subdirectory under the var directory.

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

6. while loop

Syntax of while loop:

1. while Condition test
2. do
3.   Execute command
4. done

explain:

Line 1, first perform the condition test. If the returned value is 0 (the condition test is true), enter the loop and execute the command area. Otherwise
 Do not enter the cycle, introduction while command
 Line 3, execute the command area. Among these commands, there should be a command to change the condition test. In this way, there is a chance to
 End execution after limited steps while Loop (unless you want to execute an infinite loop).
Line 4, return to line 1, execute while command

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

2, Christmas tree script file

#!/bin/bash
#Write a Christmas tree with shell
#Created on December 21, 2021
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 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_year  Merry Christmas!!!
color=122
tput setaf $color; tput bold
tput cup $((lin + 1)) $((c - 10)); echo Official account:  a bite Linux!
let c++
k=1

#Decorate it
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]}; echo \*
            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 in  a bite Li nu x!
        do
            tput cup $((lin+1)) $((c+sh))
            echo $l
            let sh++
            let sh++
            sleep 0.02
        done
    }
    k=$((k % 2 + 1))
done

3, Execute script

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

What are you waiting for? Hurry up and run!

Topics: shell