简体   繁体   English

如何将bash / awk命令放入变量(不输出命令)

[英]How to put bash / awk commands into a variable ( not output of commands)

I am trying to just put bash commands into a variable and later run with exit code function. 我试图只是将bash命令放入一个变量中,然后使用退出代码功能运行。

command1="$(awk -v previous_date=$reply -f $SCRIPT_HOME/tes.awk <(gzip -dc $logDir/*) > $OUTFILE)" # Step 1

check_exit $command1 # Step2

Here it runs the command in step 1 and always returns 0 exit code. 在这里,它运行步骤1中的命令,并且始终返回0退出代码。

How Can I put commands in a variable and later run with exit function. 如何将命令放入变量中,然后再使用退出功能运行。

You can declare your function this way: 您可以通过以下方式声明函数:

function command1 { 
    awk -v "previous_date=$reply" -f "$SCRIPT_HOME/tes.awk" <(gzip -dc "$logDir"/*) > "$OUTFILE"
}

Or the older form: 或更旧的形式:

command1() { 
    awk -v "previous_date=$reply" -f "$SCRIPT_HOME/tes.awk" <(gzip -dc "$logDir"/*) > "$OUTFILE"
}

Take attention on placing variables inside double quotes to prevent word splitting and pathname expansion. 注意将变量放在双引号内以防止单词分裂和路径名扩展。

Some POSIXists would prefer that you use the old version for compatibility but if you're just running your code with bash, everything can just be a preference. 一些POSIXists宁愿您使用旧版本来实现兼容性,但是如果您仅使用bash运行代码,则所有内容都可以作为首选项。

And you can also have another function like checkexit which would check the exit code of the command: 您还可以使用另一个功能,例如checkexit ,它可以检查命令的退出代码:

function checkexit {
    "$@"
    echo "Command returned $?"
}

Example run: 示例运行:

checkexit command1

Try using a function: 尝试使用功能:

do_stuff() { echo "$var"; echo that; }

You can later call this function and check the error code: 您以后可以调用此函数并检查错误代码:

$ var="this"
$ do_stuff
this
that
$ echo $?
0

The variables defined in the global scope of your script will be visible to the function. 在脚本的全局范围内定义的变量将对函数可见。

So for your example: 因此,对于您的示例:

command1() { awk -v previous_date="$reply" -f "$SCRIPT_HOME/tes.awk" <(gzip -dc "$logDir/*") > "$OUTFILE"); }

check_exit command1

By the way, I put some quotes around the variables in your function, as it's typically a good idea in case their values contain spaces. 顺便说一句,我在函数中的变量周围加上了一些引号,因为如果它们的值包含空格,通常是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM