如何编写一个传递给printf的参数数量可变的函数



如何修复下面的print_error函数:

#!/bin/bash
script_name="tmp.bash"
function print_error {
format="$1"
shift
printf "%s: ERROR: %sn" "$script_name" "$format" "$@"
}
print_error "Today is %s; tomorrow is %s" "$(date)" "$(date -d "+1 day")"

从而输出:

tmp.bash: ERROR: Today is Mon Nov 22 15:10:40 PST 2021; tomorrow is Tue Nov 23 15:10:50 PST 2021

目前,它输出:

tmp.bash: ERROR: Today is %s; tomorrow is %s
Mon Nov 22 15:10:40 PST 2021: ERROR: Tue Nov 23 15:10:50 PST 2021

print_error应该能够接受可变数量的参数。

使用中间变量(此处为substr(构建功能消息(日期消息(,并为技术消息(错误消息(构建第二个变量:

#! /bin/bash
declare -r script_name="tmp.bash"
function print_error {
local substr=
printf -v substr "$1" "${@:2}"
printf "%s: ERROR: %sn" "$script_name" "$substr"
}
print_error "Today is %s; tomorrow is %s" "$(date)" "$(date -d "+1 day")"

然后,您可以将功能和技术构建分开:

#! /bin/bash
declare -r script_name="tmp.bash"
function print_tech_error () {
printf "%s: ERROR: %sn" "$script_name" "$1"
}
function print_fct_error {
local substr=
printf -v substr "$1" "${@:2}"
print_tech_error "${substr}"
}
print_fct_error "Today is %s; tomorrow is %s" "$(date)" "$(date -d "+1 day")"

相关内容

  • 没有找到相关文章

最新更新