Advanced Bash-Shell Guide (Version 10) Learning Notes 3
There are more scripts in the book that record more useful scripts.
A better way to check whether the command line argument is a number
40 # E_WRONGARGS=85 # Non-numerical argument (bad argument format). 41 # 42 # case "$1" in43 # ") lines=50;;44 # * [! 0-9] *) echo" Usage: `basename $0` lines-to-cleanup "; 45 # exit $Elastic WRONGARGSTANT 46 # *) lines=$1;;47 # esac
A better way to check whether the number of command line arguments is correct
1 E_WRONG_ARGS=852 script_parameters= "- a-h-m-z" 3 #-a = all,-h = help, etc.45 if [$#-ne $Number_of_expected_args] 6 then7 echo "Usage: `basename $0` $script_parameters" 8 # `basename $0` is the script's filename.9 exit $E_WRONG_ARGS10 fi
A better way to check if it is in the correct directory
63 # cd / var/log | | {64 # echo "Cannot change to necessary directory." > & 265 # exit $eBay XCDT 66 #}
Back up the files in the source directory and extract them in the destination directory
(cd / source/directory & & tar cf -. ) | (cd / dest/directory & & tar xpvf -) A more efficient script is cd source/directory# tar cf -. | | (cd. / dest/directory; tar xpvf -) or cp-a / source/directory/* / dest/directory# cp-a / source/directory/* / source/directory/. [^.] * / dest/directory#, a hidden file in the replication source directory |
Back up files that have changed in the last 24 hours
#! / bin/bashBACKUPFILE=backup-$ (date +% m-%d-%Y) archive=$ {1:-$BACKUPFILE} # if no argument is specified on the command line, it is in the format # it will default to "backup-MM-DD-YYYY.tar.gz." tar cvf-`find. -mtime-1-type f-print `> $archive.targzip $archive.tarecho "Directory $PWD backed up in archive file\" $archive.tar.gz\ "."
If there are too many files or if the file name has white space characters, the above script may make an error
A better backup scheme tar-r appends to the archive file
#-# find. -mtime-1-type f-print0 | xargs-0 tar rvf "$archive.tar" or # find. -mtime-1-type f-exec tar rvf "$archive.tar"'{}'\; exit 0
Get the last parameter of the command line argument
Args=$# # Number of args passed.lastarg=$ {! args} # Note: This is an * indirect reference* to $args... # Or: lastarg=$ {! #}
${file#*/}: remove the first / and the string to its left: dir1/dir2/dir3/my.file.txt
${file##*/}: remove the last / and the string to its left: my.file.txt
${file#*.}: take off the first one. And the string to its left: file.txt
${file##*.}: remove the last one. And the string to its left: txt
${file%/*}: remove the last line / and the string to its right: / dir1/dir2/dir3
${file%%/*}: remove the first / and the string to the right: (null)
${file%.*}: remove the last one. And the string to the right: / dir1/dir2/dir3/my.file
${file%%.*}: take off the first one. And the string to the right: / dir1/dir2/dir3/my