Scripts in .bashrc to automatically create a directory for each day‘s terminal session records

You can modify the script in your `.bashrc` to automatically create a directory for each day's terminal session records. This way, all logs from the same day will be stored in their respective directories, making it easier to organize and manage your logs over time. Below are the steps to achieve this:

Modify `.bashrc` to Create Daily Folders for Logs

1. Open `.bashrc`:

   Open your `.bashrc` file with your preferred text editor. Here, I'll use `nano`:

   nano ~/.bashrc
2. Add Modified Script:

   Append the following lines to the `.bashrc` file. This script will create a new directory for each day and store the log files within those directories:

   if [ "x$SESSION_RECORD" = "x" ]
   then
       SESSION_RECORD=1
       export SESSION_RECORD
       DAY_DIR="/path/to/log/folder/$(date +%Y-%m-%d)"
       mkdir -p $DAY_DIR
       LOG_FILE="$DAY_DIR/$(date +%H%M%S).txt"
       script -a $LOG_FILE
       # Optionally clean up the log file after the session
       sed -i -r 's/\x1b\[[0-9;]*[mGKHJ]|\x1b\]0;[^\a]*\a//g' $LOG_FILE
       exit
   fi

Replace `/path/to/log/folder/` with the actual directory where you want the log folders to be created. This script first defines a directory based on the current date, ensures the directory exists (`mkdir -p`), and then starts a new log file within this directory.

3. Save and Exit:

   After adding the lines, save the changes (`Ctrl+O`, then `Enter` for nano) and exit the editor (`Ctrl+X` for nano).

4. Activate the Changes:

   To make the changes effective immediately, source the `.bashrc`:

   source ~/.bashrc

Explanation:

- `$DAY_DIR` Variable: This variable constructs the path to the directory where logs for each day will be stored. It uses the `date +%Y-%m-%d` command to format the directory name with the current year, month, and day.
- `mkdir -p $DAY_DIR`: This command ensures that the directory for the day's logs exists. If it doesn't, `mkdir -p` creates it. The `-p` flag prevents errors if the directory already exists.
- `$LOG_FILE`: The log file path includes the time of day to ensure each file is unique within its daily directory.
- Cleaning Up Logs: The optional `sed` command cleans up ANSI escape sequences. If you don't need this step or find it unnecessary for your purposes, you can remove it.

This setup will organize your logs neatly by date, making it easier to navigate through them based on when the terminal sessions occurred. This is particularly useful for maintaining logs over an extended period.

  • 14
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值