【问题标题】:How to write a "bash script.sh argument " [closed]如何编写“bash script.sh 参数” [关闭]
【发布时间】:2018-06-11 01:32:09
【问题描述】:

你好,有人可以帮我解决这个问题吗?

如何编写一个以文件名作为参数并以这种方式准确显示其修改日期和时间的脚本:

[user@localhost...]$ bash script.sh temp.txt
the file temp.txt was modified on May 1 20:20

然后修改该脚本,使其列出名称包含给定模式的目录的修改日期:

[user@local....]$ bash script.sh testRegex Pub
the file testRegex was modified on May 1 20:22
the directory /home/user/Public was modified on Dec 26 08:00
the directory /home/user/Pubs. was modified on May 2 20:00

请帮我快速回答这个问题

谢谢

【问题讨论】:

标签: linux bash


【解决方案1】:

这实际上很简单。您应该阅读@John Bollinger 所说的stat 命令。我还使用了date 命令来格式化日期。你可以阅读为脚本接受参数here

将所有这些结合起来会得到 -

#!/bin/bash

filename=$1;
dirname=$2;

file_mod_date=`date -d @$( stat -c %Y $1 ) +%m" "%B" "%H:%M`;

echo "The file ${filename} was modified on ${file_mod_date}";
if [ "$2" == "" ]; then
    exit 1;
else
for i in /home/user/*${dirname}*/; do
    dir_mod_date=`date -d @$( stat -c %Y $i ) +%m" "%B" "%H:%M`;
    echo "The directory ${i} was modified on ${dir_mod_date}";
done
fi

【讨论】:

  • 哈哈,那你不应该做这项工作
【解决方案2】:

一个很好的方法是传递选项和值:

例如:

file_name=""
help_message="To use this script type script.sh --file /path/to/file.txt"
# -- Get input options (if any)
while [[ $# > 0 ]] ;do
    key="$1"
    case ${key,,} in
        -f|--file)
            file_name="${2,,}"
            shift
        ;;
        -h|--help)
            echo -e "$help_message"
            exit;
            shift
        ;;
    esac
    shift
done

这样调用脚本:

bash script.sh -f "temp.txt"

关于脚本的“逻辑”,你必须弄清楚;-)

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2021-03-21
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多