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#
- Delete all files in a folder but not the folder itself
[root@server-ai ~]# find . -type f | xargs rm -f
- Copy only the structure of the directory without copying the contents of the directory
[root@server-ai ~]# find ~ -type d -exec mkdir -p demo/\{\} \;
- 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
-
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