【问题标题】:Bash script programming for inputing text through terminal and time to a log file用于通过终端输入文本和时间到日志文件的 Bash 脚本编程
【发布时间】:2012-03-11 10:32:35
【问题描述】:
我是 bash 脚本编程的新手。
我想实现一个 bash 脚本deploymLog,它接受一个字符串参数(名称)作为输入
例如:
[root@localhost Desktop]# ./deploymLog.sh name
这里我想通过终端传递字符串参数。
作为初始步骤,我需要将当前时间戳连同此输入字符串附加到日志文件中,例如当前目录中的Logone.txt,格式如下
[name]=[System time timestamp1]
【问题讨论】:
标签:
bash
shell
logging
scripting
【解决方案1】:
我不确定,我明白你想要什么。
#!/bin/bash
LOGFILE="Logone.txt"
if [ $# -eq 0 ];then
echo "Failed, please enter a name" >&2
exit 1
fi
if [ $# -gt 1 ];then
echo "Too much arguments" >&2
exit 1
fi
echo "$1=`date +%s`" >> $LOGFILE
这个小脚本将名称和系统时间戳添加到名为 Logone.txt 的文件中。
例如:
$ ./deploymLog Marcel
$ ./deploymLog Jean
$ ./deploymLog Picsou
$ cat Logone.txt
Marcel=1329798949
Jean=1329798956
Picsou=1329798963
编辑:此脚本适用于 Unix bash 而不是批处理,我认为您希望它在 windows 批处理下,将您的 bash 更改为 batch 在你的描述中避免混淆,对不起,我不能帮助你,我对批处理一无所知。
【解决方案2】:
#!/bin/sh
# 检查是否给出了一个参数
测试 $# = 1 || { 回显用法:$(basename $0) 名称; 1号出口; } >&2
exec >> Logone.txt # 将输出重定向到日志文件
printf "[%s]=[%s]\n" "$1" "$(date)" # print [name]=[timestamp]