我有一个运行良好的以下循环:
function uppercase_all_letters() {
for filename in *;
do echo "${filename^^}";
done;
}
如何"${filename^^}"
作为参数提供给函数?
我像往常一样尝试了(SUBSTITUTION="${filename^^}"
),但 Bash 报告:
./test.sh: line 26: ${filename^^}: bad substitution
答案1
要从字面上做到这一点,您可能必须求助于 eval:
function subst_all_filenames() {
subst="$1"
for filename in *
do
eval 'echo ${filename'"$subst"'}'
done
}
subst_all_filenames "^^"
subst_all_filenames ",,"
subst_all_filenames ""
或者,仅支持已知的替换列表:
function subst_all_filenames() {
case "$1" in
^^) for filename in *; do echo "${filename^^}"; done ;;
,,) for filename in *; do echo "${filename,,}"; done ;;
*) printf "%s\n" * ;;
esac
}
有时,这样的辅助函数根本就没有必要。 shell 脚本中到处都有这样的循环是很正常的。