我正在使用“高级Bash脚本编写指南”创建我的第一个脚本。
其中一个练习要求一个脚本,一旦运行,就会将输出保存到日志文件中。
我设法创建了我的第一个基本脚本,但是在最后一部分遇到了麻烦。该脚本必须包含用于创建日志文件的代码,但我只能在shell中单独执行。
该文件名为myFirstShellScript.txt。当我运行./myFirstShellScript.txt时,脚本会运行。脚本运行后,如果我在shell中键入./myFirstShellScript.txt > myFirstShellScriptLog
,则会使用输出创建新文件。现在,我尝试在脚本中添加此行,但输出的文件为空。
这是我的第一个剧本,请不要笑。
#! /bin/bash
# show todays date and time
echo "Todays date is $(date +%j)."
# Show who is currently logged into the system
echo $(who)
# show system uptime
echo $(uptime)
# log output in separate file using redirect
exit
我需要做什么(用尽可能简单的英语)让脚本自己创建输出文件,而不是一旦运行就必须在shell中单独执行?
答案 0 :(得分:5)
通常会将部分封装到(
)
,例如:
#!/bin/bash
(
# show todays date and time
echo "Todays date is $(date +%j)."
# Show who is currently logged into the system
echo $(who)
# show system uptime
echo $(uptime)
) > myFirstShellScriptLog
答案 1 :(得分:4)
您可以使用exec
builtin命令将脚本的输出重定向到脚本中的文件中:
#! /bin/bash
# Save output to "log.txt"
exec > log.txt
# show todays date and time
echo "Todays date is $(date +%j)."
...