Scripting tutorials for shell to back up files, rename files, and delete specified files
This article introduces the "shell backup files, rename files, delete specified files scripting tutorial" related knowledge, in the actual case of the operation process, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!
1. Back up the files under the directory
The code is as follows:
#! / bin/bash
E_BADARGS=65
Case $# in / / $# indicates the number of parameters transferred. Sh bak.sh. / .sh has two parameters. / and .sh
0) / / if the parameter is empty, an error is prompted and exit
Echo "message:param is wrong"
Exit $E_BADARGS
Esac
String= ""
Cd $1 / / enter the incoming directory
/ / parameters should also be connected to the files in the backup subdirectory
If [$#-gt "1"]
Then
String=$string "" $2
Fi
For filename in * / / read the files in the current directory
Do
If [- d "$filename"] / / check whether it is a directory or not
Then
/ bin/sh / home/zhangy/test/$0 $(pwd) / $filename $string / / Recursive if it is a directory
Else
If [$#-gt "1"] & & [${filename: (- ${# 2})} = $2] / / specify what files to back up
Then
Cp $filename $filename "bak"
Fi
If [$#-eq "1"]
Then
Cp $filename $filename "bak" / / unspecified, back up all files in the directory
Fi
Fi
Done
Exit 0
[zhangy@BlackGhost test] $sh bak.sh. / .sh means to back up all files in the current directory (and subdirectories) with the suffix .sh.
2, rename the file
The code is as follows:
#! / bin/bash
E_BADARGS=65
Case $# in
0 | 1 | 2)
Echo "message:param is wrong"
Exit $E_BADARGS
Esac
String= ""
Cd $1
If [$#-gt "2"]
Then
String=$string "$2" $3
Fi
For filename in *
Do
If [- d "$filename"]
Then
/ bin/sh / home/zhangy/test/$0 $(pwd) / $filename $string
Else
If [$#-gt "2"] & [${filename: (- ${# 2})} = $2]
Then
Mv $filename ${filename%$2} $3
Fi
Fi
Done
Exit 0
[zhangy@BlackGhost test] $sh rename.sh / home/zhangy/test .php .html means that all files in the current directory (including subdirectories) with the suffix .php are renamed to .html
3. Delete the specified file
The code is as follows:
#! / bin/bash
E_BADARGS=65
Case $# in
0 | 1)
Echo "message:param is wrong"
Exit $E_BADARGS
Esac
String= ""
Cd $1
If [$#-gt "1"]
Then
String=$string "" $2
Fi
For filename in *
Do
If [- d "$filename"]
Then
/ bin/sh / home/zhangy/test/$0 $(pwd) / $filename $string
Else
If [$#-gt "1"] & & [${filename: (- ${# 2})} = $2]
Then
Rm-f $filename
Fi
Fi
Done
Exit 0
[zhangy@BlackGhost test] $sh del.sh / home/zhangy/test .log delete / home/zhangy/test, and all files in the subdirectory with the suffix .log
This is the end of the scripting tutorial for shell backing up files, renaming files, and deleting specified files. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!