2

How can I achieve casing text like this:

string="this is a string"
for case in u l c
do
    declare -"${case}" out
    out=$string
    echo $out
done
#THIS IS A STRING
#this is a string
#This is a string

with looping through the names of declared variables:

declare -u UPPER
declare -l LOWER
declare -c CAPITALIZE
for i in UPPER LOWER CAPITALIZE
do
    i=$string
    echo $i
done
#this is a string
#this is a string
#this is a string

(note all lower case)

Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72

3 Answers3

5

You may use it like this:

string="this is a string"
declare -u UPPER
declare -l LOWER
declare -c CAPITALIZE

for i in UPPER LOWER CAPITALIZE; do
    declare $i="$string" # assign value to each var
    echo "$i='${!i}'"    # print each var
done

Output:

UPPER='THIS IS A STRING'
LOWER='this is a string'
CAPITALIZE='This is a string'
anubhava
  • 761,203
  • 64
  • 569
  • 643
4

Use a nameref:

for i in UPPER LOWER CAPITALIZE; do
    declare -n var=$i  # variable `var` is a ref to variable named in $i
    var=$string
    echo "$var"
done
THIS IS A STRING
this is a string
This is a string
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

I'd do something like this, with a function to return its argument with a new case:

#!/usr/bin/env bash

function recase() {
    case "$1" in
        UPPER) local -u str="$2";;
        LOWER) local -l str="$2";;
        CAPITALIZE) local -c str="$2";;
    esac
    printf "%s\n" "$str"
}

string="this is a string"
for c in UPPER LOWER CAPITALIZE
do
    recase "$c" "$string"
done
Shawn
  • 47,241
  • 3
  • 26
  • 60