Tri*_*daz 24 scripting bash shell-script
我有一个 bash 脚本,其中包含基于我在调用它时传入的命令行参数的各种 if 语句。关于正在运行的命令的某种输出有助于确认所有这些 if 语句的流程,但我当前的解决方案给了我太多信息。
set -v在脚本中使用对于查看在脚本中运行时打印到屏幕上的命令有些帮助,但是我得到了太多命令。它几乎就像脚本的完整副本。
我想要显示正在运行的命令的输出,但我不想在 if 语句中看到注释、新行、表达式等。
有没有办法在打印之前首先通过正则表达式传递 -v 选项生成的所有可能的输出?或者其他一些解决方案让 bash 只输出某种“类型”的命令(例如,使用可执行文件而不仅仅是 bash 特定的语句、注释等?)
[1] /sf/ask/18033151/对此非常有帮助,也是我得到使用建议的地方set -v。
编辑:
与我正在运行的脚本类似(但不完全相同)的脚本:
#!/bin/bash
#get verbose command output
set -v
env=$1
if [ "$env" == "dev" ]; then
python ascript.py
fi
if [ "$env" == "prod" ]; then
#launching in prod will most likely fail if not run as root. Warn user if not running as root.
if [ $EUID -ne 0 ]; then
echo "It doesn't look like you're running me as root. This probably won't work. Press any key to continue." > /dev/stderr
read input
fi
#"stop" any existing nginx processes
pkill -f nginx
nginx -c `pwd`/conf/artfndr_nginx.conf
fi
Run Code Online (Sandbox Code Playgroud)
我只想要来自这个脚本的 2 组可能的输出行。首先:
python ascript.py
Run Code Online (Sandbox Code Playgroud)
第二:
pkill -f nginx
nginx -c /some/current/directory/conf/artfndr_nginx.conf
Run Code Online (Sandbox Code Playgroud)
小智 18
使用子外壳,即:
( set -x; cmd1; cmd2 )
Run Code Online (Sandbox Code Playgroud)
例如:
( set -x; echo "hi there" )
Run Code Online (Sandbox Code Playgroud)
印刷
+ echo 'hi there'
hi there
Run Code Online (Sandbox Code Playgroud)
ter*_*don 13
当我编写更复杂的 bash 脚本时,我使用一个小函数来运行命令,这些命令也会将运行的命令打印到日志文件中:
runthis(){
## print the command to the logfile
echo "$@" >> $LOG
## run the command and redirect it's error output
## to the logfile
eval "$@" 2>> $LOG
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的脚本中,我运行如下命令:
runthis "cp /foo/bar /baz/"
Run Code Online (Sandbox Code Playgroud)
如果您不想打印命令,只需正常运行即可。
您可以将 设置$LOG为文件名,也可以将其删除并打印到标准输出或标准错误。
| 归档时间: |
|
| 查看次数: |
27296 次 |
| 最近记录: |