Yige

Yige

Build

Basic Shell Scripting

Basics of Shell Scripting#

Shell Script Debugging#

-n, read the commands in the script without executing them, used to check for syntax errors in the script
-v, execute the script while printing the executed script commands to standard error output
-x, provide tracing execution information, printing each executed command and its result sequentially

Sorting an Unordered Column of Numbers in Text with Shell Script#

[root@server ~]# sort -n 190307.txt | awk '{a+=$0;print$0} END {print "sum="a}'

Shell Command to View Line Numbers of Empty Lines in a File#

[root@server ~]# grep -n ^$ filename
[root@server ~]# sed -n '/[a-zA-Z0-9@#$%^&*]!=' filename
[root@server ~]# sed -n '/^$/=' filename
[root@server ~]# awk '/^$/{print NR}' filename

Shell Folder Operations#

  1. Delete all files in a folder but not the folder itself
[root@server-ai ~]# find . -type f | xargs rm -f
  1. Copy only the structure of the directory without copying the contents of the directory
[root@server-ai ~]# find ~ -type d -exec mkdir -p demo/\{\} \;
  1. Find all text files in the current folder that contain the character "math" in their content
[root@server-ai ~]# grep -r "math" /home/chenjiawei/test/shell/ | cut -d ":" -f 1
  1. Traverse all files in the directory and its subdirectories

    #! /bin/bash
    function read_dir(){
        for file in `ls $1`       # Note that there are two backticks here, indicating a system command
        do
            if [ -d $1"/"$file ]  # Note that there must be a space here, otherwise it will report an error
            then
                read_dir $1"/"$file
            else
                echo $1"/"$file   # Process the file here
            fi
        done
    }
    # Read the first argument
    read_dir $1
    

    Execute the command

    $ sh traveDir.sh DIR_NAME
    
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.