如何从变量附加命令的其余部分?
How to append the rest of the command from a variable?
在下面的示例中,当变量 cpstdout
设置为 1 时,我想在屏幕上打印文本并将此文本附加到文件中。否则只在屏幕上打印文本。我需要使 append
变量的回声部分灵活。有什么方法可以更正我的代码吗?
#!/bin/ksh
cpstdout=1
if [ $cpstdout -eq 1 ]; then
append="| tee somefile"
else
append=""
fi
echo "test string" $append
现在的结果是这样的:
./test.sh
test string | tee somefile
-当然没有创建文件
打印函数示例:
print_output(){
printf "\t/-------------------------------------------------\ \n"
for i in "$@"; do
printf "\t| %-14s %-32s |\n" "$(echo $i | awk -F, '{print }')" "$(echo $i | awk -F, '{print }')"
shift
done
printf "\t\-------------------------------------------------/\n"
}
将附加命令定义为函数:
output_with_append() {
tee -a somefile <<<""
}
然后,在if
中设置一个变量为合适的输出函数:
if [ $cpstdout -eq 1 ]; then
output=output_with_append
else
output=echo
fi
最后,对运行命令使用变量扩展:
$output "test_string"
请注意,我使用了 tee -a
因为你说你想附加到文件而不是覆盖它。
将 cpstdout
设置为 </code> 以便我们可以通过命令行参数控制它:</p>
<pre><code>cpstdout=""
示例会话如下所示:
$ ./test.sh 1
test_string
$ ./test.sh 1
test_string
$ cat somefile
test_string
test_string
$ ./test.sh 0
test_string
$ cat somefile
test_string
test_string
在下面的示例中,当变量 cpstdout
设置为 1 时,我想在屏幕上打印文本并将此文本附加到文件中。否则只在屏幕上打印文本。我需要使 append
变量的回声部分灵活。有什么方法可以更正我的代码吗?
#!/bin/ksh
cpstdout=1
if [ $cpstdout -eq 1 ]; then
append="| tee somefile"
else
append=""
fi
echo "test string" $append
现在的结果是这样的:
./test.sh
test string | tee somefile
-当然没有创建文件
打印函数示例:
print_output(){
printf "\t/-------------------------------------------------\ \n"
for i in "$@"; do
printf "\t| %-14s %-32s |\n" "$(echo $i | awk -F, '{print }')" "$(echo $i | awk -F, '{print }')"
shift
done
printf "\t\-------------------------------------------------/\n"
}
将附加命令定义为函数:
output_with_append() {
tee -a somefile <<<""
}
然后,在if
中设置一个变量为合适的输出函数:
if [ $cpstdout -eq 1 ]; then
output=output_with_append
else
output=echo
fi
最后,对运行命令使用变量扩展:
$output "test_string"
请注意,我使用了 tee -a
因为你说你想附加到文件而不是覆盖它。
将 cpstdout
设置为 </code> 以便我们可以通过命令行参数控制它:</p>
<pre><code>cpstdout=""
示例会话如下所示:
$ ./test.sh 1
test_string
$ ./test.sh 1
test_string
$ cat somefile
test_string
test_string
$ ./test.sh 0
test_string
$ cat somefile
test_string
test_string