Shell指令碼記錄日誌到檔案

2022-02-21 08:50:56 字數 1480 閱讀 6435

shell指令碼基本技能是設定變數,輸出資訊。

1、記錄日誌

sh指令碼輸出到控制台,並且寫入日誌檔案: 

#!/bin/bash

#檔名:test.

shname="

xiongzaiqiren

"echo

$name

echo

"backup date:

" $(date +"

%y-%m-%d %h:%m:%s")

date=`date

'+%y%m%d-%h%m%s'`

echo

$date

lognamedate=`date

'+%y%m%d'`

echo

"" >>log$lognamedate.log

echo

"———————————————–

" >>log$lognamedate.log

echo

"backup date:

" $(date +"

%y-%m-%d %h:%m:%s

") >>log$lognamedate.log

echo

"———————————————–

" >> log$lognamedate.log

執行指令碼,會在當前目錄下生成  log20190826.log檔案,開啟它發現成功寫入日誌資訊:

2、時間格式輸出

當前日期格式輸出:

#將當前時間和包含換行符的文字內容輸出到檔案

echo -e $(date) "

\nhello world !

" >>test.txt

#將當前時間(格式化)和包含換行符的文字內容輸出到檔案

echo -e `date

'+%y-%m-%d %h:%m:%s %a

'` "

\nhello world !

" >>test.txt

#同上,簡化版。

echo -e `date

'+%f %t %a

'` "

\nhello world !

" >>test.txt

#輸出到以日期格式檔案名

echo -e $(date) "

\nhello world !

" >> test`date +'

%y-%m-%d

'`.txt

檢視 mylog/test.txt 內容如下:

參考:shell指令碼按當前日期輸出日誌

shell指令碼定時清除日誌檔案

bin bash clearfile 獲取資料夾內,檔案大小 m為單位 和檔案路徑 呼叫clear函式清空檔案 clear filesizeandfile clear echo 檔案大小 filesize echo 檔案路徑 filepath echo 磁碟空間 disksize 獲取檔名 file...

日誌記錄重定向到檔案

開啟檔案 fp fopen mnt sdcard com.log at if fp null 重定向檔案 oldstdout dup std out dup2 fileno fp std out oldstderr dup std err dup2 fileno fp std err 限定日誌檔案大...

shell指令碼記錄

size x large shell size case語法 case 1 in start start stop stop usage esac 檢視系統32位還是64位 uname m x86 64 arch x86 64 size x large grep size grep命令hang住的問...