1

I have a following loop that works well:

function uppercase_all_letters() {
  for filename in *;
    do echo "${filename^^}";
  done;
}

How do I provide "${filename^^}" as a parameter to the function?

I tried it the usual well (SUBSTITUTION="${filename^^}") but then Bash reports:

./test.sh: line 26: ${filename^^}: bad substitution
  • You are obviously not running the code with bash, but possibly with dash (/bin/sh on some Linuxes) or zsh, although dash would have said Bad substitution (upper case B) and would also have complained about the non-standard function definition. – Kusalananda Jul 17 '19 at 6:48
  • @Kusalananda Only bash is using that error format; eg. echo '${foo&&}' | bash => bash: line 1: ${foo&&}: bad substitution. The OP is probably using some older version of bash which didn't support yet that syntax. – mosvy Jul 17 '19 at 7:53
  • Could you please mention the version of bash that you use? The ^^ thing was added in bash-4.0-alpha. – Kusalananda Jul 17 '19 at 7:58
  • @mosvy I think I misunderstood what the user wanted. It would have made more sense if the code that uses $SUBSTITUTION (and which is what probably causes the error) was shown. – Kusalananda Jul 17 '19 at 8:03
  • Yes, but who's printing that error? ;-) – mosvy Jul 17 '19 at 8:04
0

To do it literally, you'd probably have to resort to 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 ""

Alternatively, support only a known list of substitutions:

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
}

Sometimes such a helper function also isn't even necessary in the first place. It's quite normal to have such loops all over the place in a shell script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.