2021-01-14 VIM and Shell

VIM

Vim is a highly configurable text editor built to make creating and changing any kind of text very efficient. It is included as "vi" with most UNIX systems and with Apple OS X.

control mode: manipulate cursor movement, copy, paste, delete, search, etc...
input mode: basic text input
last line mode: configure the editor options, save, quit, etc...

vim basic editing

vim frequently used commands

  • dd ???delete the line where the cursor is
  • 2dd ?delete 2 lines starts from the current cursor
  • yy ???copy the entire line of data from the current cursor
  • 2yy ?copy 2 lines starts form the current cursor
  • n ?????locate the next string that matches the searching pattern
  • N ?????locate the previous string that matches the searching pattern
  • u ?????undo the previous manipulation
  • p ?????paste the text data from the last dd or yy right after the cursor

Last Line Mode commands

  • :w ? ? ? ? ? ?????????????save the file
  • :q ? ? ? ? ? ?????????????exit the current text file
  • :q! ? ? ? ? ? ???????????forced to exit the current text file which will lose all the unsaved text content
  • :wq! ? ? ? ? ?????????forced to save and exit the current text file
  • :set nu ? ? ? ? ?????show line numbers
  • :set nonu ? ? ? ? ?disable line numbers
  • :command ? ? ? ??execute the eligible commands(inside of vim editor)
  • :integer ?? ? ? ? ????jump to the specified line number
  • :s/one/two ?? ? ? ?at the current line, search one and replace the first one by two
  • :s/one/two/g ? ? ?at the current line, search one and replace all the one by two
  • :%s/one/two/g ?search the entire text file and replace one by two
  • ?string ? ? ? ? ? ? ?serach specified pattern from bottom to top
  • /string ? ? ? ? ? ? ? ?search specified pattern from top to bottom

Tricks

select all(high light):press esc,then ggvG or ggVG
copy all:press esc,then ggyG
delete all:press esc,then ggdG

gg:move cursor to the first line,it only works on vim
v : enter the visual mode
G :move cursor to the last line
select the data content,then:
d delete the selected portion
y copy the selected portion to 0registor
+y copy the selected portion to +registor, i.e. the system clipboard, then other programs can use it

Practise

  • add new data without :w
# The following line just be added without :w
select all(high light):press esc,then ggvG or ggVG
copy all:press esc,then ggyG
delete all:press esc,then ggdG

E37: No write since last change (add ! to override) 
  • change hostname
vim /etc/hostname
(base) /loveplay1983@($)-> hostname
deepgiant
  • configure network

Shell Script

https://linuxhint.com/30_bash_script_examples/
https://www.ubuntupit.com/simple-yet-effective-linux-shell-script-examples/
https://www.softwaretestinghelp.com/shell-scripting-interview-questions/

What is a Shell?

At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions.

Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNU utilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users or groups to establish custom environments to automate their common tasks.

Practise

  • Create a simple script
# .sh extension indicates this file is a shell script file
# #!/bin/bash tells the system to use the bash interpreter to execute the script

#!/bin/bash
pwd
ls -al
  • run the shell script
(base) /loveplay1983@($)-> ./example.sh
bash: ./example.sh: Permission denied
(base) /loveplay1983@($)-> chmod u+x example.sh
(base) /loveplay1983@($)-> ./example.sh 
  • Accept user input or args

    image.png

    # .sh extension indicates this file is a shell script file
    # #!/bin/bash tells the system to use the bash interpreter to execute the script
    
    #!/bin/bash
    echo "script name => $0"
    echo "total number of args => $#"
    echo "the 1st parameter is $1, the 5th parameter is $5"
    
    (base) /loveplay1983@($)-> ./example.sh x1 x2 x3 x4 x5
    script name => ./example.sh
    total number of args => 5
    the 1st parameter is x1, the 5th parameter is x5
    
  • Conditional test
    Shell script can use the conditional statement for testing the expression, 0 if the result is true, not non-zero otherwise
    [\, conditional-statement\, ] \Leftarrow Notice the right space
    \Uparrow
    Notice the left space

    • -d ?????test whether the target is directory
    • -e ?????test whether the file exists
    • -f ?????test whether the file is an ordinary file
    • -r ?????test the read permission
    • -w ???test the write permission
    • -x ????test the execute permission
    [root@linuxprobe chap4_vim_shell]# cat shell-express.sh 
    #!/bin/bash
    # Warnining!, Notice the space in between the square braces
    [  -d /etc/fstab ]
    echo $?   # print out the last result  
    [  -f /etc/fstab ]
    echo $?   # print out the last result
    # logic and
    [ -e /dev/cdrom ] && echo "exist"
    # logic or 
    [ $USER = root ] || echo "user"
    # logic not
    [ $USER != root ] || echo "root"
    [root@linuxprobe chap4_vim_shell]# ./shell-express.sh 
    1
    0
    exist
    root
    root
    

    Tips:
    && / logical and : if and only if the prior expression is true
    || / logical or : if and the prior expression is false then the post expression will start
    ! / logical NOT : take the negation of the expression, e.g. true => false

    (base) /loveplay1983@($)-> [ $USER != root ] && echo "user" || echo "root"
    user
    
  • Integer comparison

    • -eq 是否等于
    • -ne 是否不等于
    • -gt 是否大于
    • -lt 是否小于
    • -le 是否等于或小于
    • -ge 是否大于或等于
    (base) /loveplay1983@($)-> echo $?
    0
    (base) /loveplay1983@($)-> [ 10 -ne 10 ]
    (base) /loveplay1983@($)-> echo $?
    1
    

    free memory detection

    #!/bin/bash
    # Detect the free memory 
    freeMem=`free -m | grep Mem: | awk '{print $4}'`
    [ $freeMem -lt 1024 ] && echo "Insufficient Memory"
    root@deepgiant:/home/loveplay1983/linux/shell# ./checkMem.sh 
    10892
    
  • String comparison

    • = check the equality of the strings
    • != check whether the strings are different
    • -z check whether the string is empty
    #!/bin/bash
    #Check equality of strings
    [ -z $1 ]
    if [ $? -eq 0 ]
    then
            echo "The string is not empty."
    else
            echo "It is an empty string."
    fi
    
    #!/bin/bash
    if [ ! $LANG = "en_US.UTF-8" ]
    then
            echo " Not en.US"
    else
            echo "en.US"
    fi
    
  • if...then...fi; if....then....else...fi; if...then...elif...then...else...fi

    #!/bin/bash
    # if then fi 
    if             # test for condition
            then   # action list
    fi             # assert the if statement is finished
    
    # if then else fi 
    if 
            then
    else
    fi
    # if then elif then else fi
    if 
             then
    elif 
             then
    else
    fi
    
    read -p "Enter your score(0-100): " GRADE
    if [ $GRADE -ge 90 ] && [ $GRADE -le 100 ]
    then
            echo "Your grade is excellent!"
    elif [ $GRADE -ge 70 ] && [ $GRADE -le 89 ]
    then
            echo "Your grade is not bad!"
    else
            echo "Your grade is a little bit sad!!!"
    fi
    
  • for loop

    # for loop will take many objects at one time and do the operations one by one
    for # take all the objects in # the object list
    do
            # actions one by one
    done      
    
    • detect and add users
    read -p "Enter the user password???" PASSWD
    for UNAME in `cat users.txt`  
    do
            id $UNAME &> /dev/null
            if [ $? -eq 0 ]
            then
                    echo "$UNAME, already exists"
            else
                    useradd $UNAME &> /dev/null
                    echo "$PASSWD" | passwd --stdin $UNAME &> /dev/null
                    echo "$UNAME, Create success"
            fi
    done
    
    • ping a list of hosts
    #!/bin/bash
    host_list=$(cat hosts.txt)
    for ip in $host_list
    do
          echo $ip
          ping -c 3 -i 0.2 -W $ip &> /dev/null
          if [ $? -eq 0 ]
          then
                  echo "Host $ip is on-line."
          else
                  echo "Host $ip is off-line."
          fi
    done
    
  • while loop
    while loop walks through a list of executions repeatedly until it meets the break, it often doesn't know the exact number of repetitions.

    while # condition
    do
            # actions
    done    
    
    # expr - evaluate the expression
    PRICE=$(expr $RANDOM % 1000)  # random number mod # will yield a random number in the range of 0-#
    TIMES=0
    echo "price is in the range of 0-999, please guess it?!!"
    while true
    do
            read -p "Enter the price: " price
            let TIMES++
            if [ $price -eq $PRICE ]
            then
                    echo "Congrats, the actual price is $PRICE"
                    echo "Total guessed number $TIMES"
                    exit
            elif [ $price -gt $PRICE ]
            then
                    echo "Too High"
            else
                    echo "Too low"
            fi
    done
    
  • case statement

    case :'var-value' in
    :'pattern'
           :'commands'
           ;;
    :'pattern'
           :'commands'
           ;;
           :'...'
    *)
           :'default commands'
    esac
    
    read -p "enter a character, end up with enter key" KEY
    case "$KEY" in
            [a-z][A-Z])
                    echo "you have entered letters"
                    ;;
            [0-9])
                    echo "you have entered digits"
                    ;;
            *)
                    echo "you have entered data other than letters and digits"
    esac
    
    

Scheduled Task

  • There at 2 ways to do the automatic tasks
    • Do something at a particular time with at command
    • Periodically do the same tasks, e.g. Backup your /home directory at each Monday Morning \Rightarrow home.backup.tar.xz
  • With at command
    https://linuxconfig.org/how-to-schedule-tasks-using-at-command-on-linux
    • -f file Reads the job from file rather than standard input
    • -q Uses the specified queue.
    • -l Display the pending job list
    • -d Delete the particular pending job
    • -m Send email to the user after the job is done

    at and batch read commands from standard input or a specified file which are to be executed at a later time, using /bin/sh.

  • at command uses interactive mode to configure the schedule
    [linuxprobe@linuxprobe ~]$ at 22:00
    warning: commands will be executed using /bin/sh
    at> apat update
    at> apt autoremove
    at> apt autoclean
    at> <EOT>  
    job 1 at Mon Jan 18 22:00:00 2021
    
    at command with pipe
    [linuxprobe@linuxprobe ~]$ echo "systemctl restart sshd"  | at 22:30
    warning: commands will be executed using /bin/sh
    job 2 at Mon Jan 18 22:30:00 2021
    
    list and delete specific schedule
    [linuxprobe@linuxprobe ~]$ at -l
    1 Mon Jan 18 22:00:00 2021 a linuxprobe
    2 Mon Jan 18 22:30:00 2021 a linuxprobe
    [linuxprobe@linuxprobe ~]$ atrm 2
    [linuxprobe@linuxprobe ~]$ at -l
    1 Mon Jan 18 22:00:00 2021 a linuxprobe
    
    Do the task after a particular timeline
    linuxprobe@linuxprobe ~]$ at now +1 HOUR
    warning: commands will be executed using /bin/sh
    at> apt clean
    at> apt autoclean
    at> <EOT>
    job 3 at Mon Jan 18 22:33:00 2021
    [linuxprobe@linuxprobe ~]$ 
    
  • With crontab command
[linuxprobe@linuxprobe home]$ systemctl status crond
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2021-01-19 01:36:47 CST; 15s ago
 Main PID: 11729 (crond)
    Tasks: 1 (limit: 49666)
   Memory: 1.1M
   CGroup: /system.slice/crond.service
           └─11729 /usr/sbin/crond -n

https://ostechnix.com/a-beginners-guide-to-cron-jobs/
https://www.tutorialspoint.com/unix_commands/crontab.htm

crontab is the program used to install, deinstall or list the tables used to drive the cron daemon in Vixie Cron. Each user can have their own crontab, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly.

One of the most useful utility that you can find in any Unix-like operating system. It is used to schedule commands at a specific time. These scheduled commands or tasks are known as "Cron Jobs". Cron is generally used for running scheduled backups, monitoring disk space, deleting files (for example log files) periodically which are no longer required, running system maintenance tasks and a lot more. In this brief guide, we will see the basic usage of Cron Jobs in Linux.

image.png
  • To display the contents of the crontab file of the currently logged in user
crontab -l
  • Edit the current user's cron jobs
crontab -e
# If the editor is selected wrongly, you may use `select-editor` to choose again
Select an editor.  To change later, run 'select-editor'.
  1. /bin/nano        <---- easiest
  2. /usr/bin/vim.basic
  3. /usr/bin/vim.tiny
  4. /bin/ed

Choose 1-4 [1]: 
  • To edit the crontab of a different user, for example loveplay1983
crontab -u loveplay1983 -e
  • Examples
# To run a cron job at every minute
* * * * * <command-to-execute>
# To run cron job at every 5th minute
*/5 * * * * <command-to-execute>
# To run a cron job at every quarter hour (i.e every 15th minute)
*/15 * * * * <command-to-execute>
# To run a cron job every hour at minute 30
30 * * * * <command-to-execute>
# You can also define multiple time intervals separated by commas. For example, the following cron job will run three times every hour, at minute 0, 5 and 10
0,5,10 * * * * <command-to-execute>
# Run a cron job every half hour i.e at every 30th minute
*/30 * * * * <command-to-execute>
# Run a job every hour (at minute 0)
0 * * * * <command-to-execute>
# Run a job every 2 hours
0 */2 * * * <command-to-execute>
# Run a job every day (It will run at 00:00)
0 0 * * * <command-to-execute>
# Run a job every day at 3am
0 3 * * * <command-to-execute>
# Run a job every Sunday
0 0 * * SUN <command-to-execute>   /   0 0 * * 0 <command-to-execute>
# Run a job on every day-of-week from Monday through Friday i.e every weekday
0 0 * * 1-5 <command-to-execute>
# Run a job every month (i.e at 00:00 on day-of-month 1)
0 0 1 * * <command-to-execute>
# Run a job at 16:15 on day-of-month 1
15 16 1 * * <command-to-execute>
# Run a job at every quarter i.e on day-of-month 1 in every 3rd month
0 0 1 */3 * <command-to-execute>   # 每季度
# Run a job on a specific month at a specific time
5 0 * 4 * <command-to-execute>
# Run a job every 6 months
0 0 1 */6 * <command-to-execute>
# Run a job every year
* * 1 1 * <command-to-execute>

We can also use the following strings to define job

@reboot                 Run once, at startup.
@yearly                 Run once a year.
@annually               (same as @yearly).
@monthly                Run once a month.
@weekly                 Run once a week.
@daily                  Run once a day.
@midnight               (same as @daily).
@hourly                 Run once an hour.

e.g.

@reboot <command-to-execute>
  • To remove all cron jobs for the current user
crontab -r
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容