如何编写传递给 printf 的参数数量可变的函数
How to write a function with a variable number of arguments that are passed to printf
如何修复下面的 print_error
函数:
#!/bin/bash
script_name="tmp.bash"
function print_error {
format=""
shift
printf "%s: ERROR: %s\n" "$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
)构建功能消息(日期消息)和技术消息(错误消息)的第二个buid:
#! /bin/bash
declare -r script_name="tmp.bash"
function print_error {
local substr=
printf -v substr "" "${@:2}"
printf "%s: ERROR: %s\n" "$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: %s\n" "$script_name" ""
}
function print_fct_error {
local substr=
printf -v substr "" "${@:2}"
print_tech_error "${substr}"
}
print_fct_error "Today is %s; tomorrow is %s" "$(date)" "$(date -d "+1 day")"
如何修复下面的 print_error
函数:
#!/bin/bash
script_name="tmp.bash"
function print_error {
format=""
shift
printf "%s: ERROR: %s\n" "$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
)构建功能消息(日期消息)和技术消息(错误消息)的第二个buid:
#! /bin/bash
declare -r script_name="tmp.bash"
function print_error {
local substr=
printf -v substr "" "${@:2}"
printf "%s: ERROR: %s\n" "$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: %s\n" "$script_name" ""
}
function print_fct_error {
local substr=
printf -v substr "" "${@:2}"
print_tech_error "${substr}"
}
print_fct_error "Today is %s; tomorrow is %s" "$(date)" "$(date -d "+1 day")"