Case II: shell script gets the current date and time and the disk case

Problem Analysis

This question has two core knowledge points:

  1. How to automatically indicate today's date 

  2. Disk Usage

Date print command to date, examples of commands as follows:

  DATE # 

  2017 Nian 12 Wednesday, 20 September 16:26:55 CST

And the title should be required format: 2017-12-20, date order is such a function, the example command follows:

  DATE Y-% +% # M-% D 

  2017-12-20 

  or: 

  #% F. + DATE 

  2017-12-20

Disk usage, we use the command df -h to achieve, the following example command:

  # Df -h 

  file system capacity has been available with a mount point with% 

  / dev / 2% Vdal 99G 92G 1.8G / 

  devtmpfs 911M 0 911M 0% / dev 

  tmpfs 920M 0 920M 0% / dev / SHM 

  tmpfs 920M 920M 336K. 1 % / RUN 

  tmpfs 920M 0 920M 0% / SYS / FS / a cgroup 

  tmpfs 184M 0 184M 0% / RUN / User / 0
Exercise answer

With the above analysis later, we finally get the answer to this question:

  #! /bin/bash

  d=`date +%F`

  logfile=$d.log

  df -h > $logfile
 
Answer Analysis

The current date assigned to the variable d, to define the daily log file name, the final result of the use of disk input directly to the log. Here>, it can compare the results of the special symbol to the left of the file is written to the right of the sign in.

Expand knowledge

1.  the shell  Anti quotation marks represent the results of a command, usually variables are assigned, sample command is as follows:

  # n=`wc -l /etc/passwd|awk '{print $1}'`

  # echo $n

  23

2. date command has many uses, for example:

  # Date +% H ## hours 

  16 

  # DATE + M% ## min 

  38 is 

  # DATE seconds + ##% S 

  55 

  # DATE + ##% T time 

  16:39:31 

  # DATE% W + ## weeks 

  3 

  # date -d "-1 day" +% F ## one day before 

  2017-12-19

3> is redirected, we run a command, have the right information is also output an error message output,> will correct output information is written to the specified file, there is a corresponding error redirection symbol 2 >, as the name suggests it will error information is written to the specified file. Examples are as follows:

  # Ls / etc / passwd / etc / nofile ## in which the / etc / nofile does not exist, it will complain 

  ls: can not access the / etc / nofile: No such file or directory 

  / etc / passwd 

  # LS / etc / passwd / etc / nofile> / tmp / log 2> / tmp / error 

  # CAT / tmp / log 

  / etc / passwd 

  # CAT / tmp / error 

  LS: can not access the / etc / nofile: no such file or directory

Guess you like

Origin www.cnblogs.com/linuxprobe-sarah/p/11183121.html
Recommended