$string=$string | tr [a-z] [A-Z] no workie

jfb
New Contributor

Hello!

I'm capturing text then echoing it to ALL CAPS like this, which proves the command works.

read diskName
echo $diskName | tr [a-z] [A-Z]

The goal is to pass this capitalized text to:

sudo diskutil partitionDisk /dev/diskn MBR fat32 "$diskName" 0b

However! My trouble is passing the ALL CAPS text to the diskutil command. So I tried:

$diskName=`"$diskName" | tr [a-z] [A-Z]`

Here's the whole piece:

read diskName
$diskName=`"$diskName" | tr [a-z] [A-Z]`
sudo diskutil partitionDisk /dev/diskn MBR fat32 "$diskName" 0b

Any thoughts?

1 ACCEPTED SOLUTION

davidacland
Honored Contributor II

Hi @jfb

This one will work:

read diskName
sudo diskutil partitionDisk /dev/disk2 MBR fat32 $(echo $diskName | tr [a-z] [A-Z]) 0b

View solution in original post

7 REPLIES 7

davidacland
Honored Contributor II

Hi @jfb

This one will work:

read diskName
sudo diskutil partitionDisk /dev/disk2 MBR fat32 $(echo $diskName | tr [a-z] [A-Z]) 0b

mm2270
Legendary Contributor III

Just as an FYI, there's also awk

echo $diskName | awk '{print toupper}'

jfb
New Contributor

@davidacland

Can you explain the use of the parenthesis and how it did what I wanted it to do?

Thank you so much!

davidacland
Honored Contributor II

My understanding is that they are mostly interchangeable, although the $() syntax is newer and preferred these days.

It's rare that I see an actual issue with the backtick syntax but this must be one of them.

mm2270
Legendary Contributor III

Actually I don't think the issue is the use of backticks here (although the $() syntax is preferable since its easier to read and less prone to be confused) The problem is that when you do this:

$diskName=`"$diskName" | tr [a-z] [A-Z]`

You are not creating a new variable because $diskName isn't being echoed first to pass it to tr. IOW, tr isn't actually receiving the captured $diskName variable to run any conversion on it. if you just changed it like so:

$diskName=`echo "$diskName" | tr [a-z] [A-Z]`

it would probably work just as well as the one posted above.

Look
Valued Contributor III

@mm2270 is right the first is just sending the output of a command stored in $diskname to tr which is probably not a valid command and if it was it certainly wouldn't be what you were after.

brock_walters
Contributor

Hey guys -

1st, I'm not sure if that 1st $ is part of the command or if it's just the prompt? Also, I agree I'm not sure I'm seeing the objective...

2nd, as to syntax, even bash version 3 which ships with OS X (the newest version is version 4...) refers to backticks as "the old-style backquote form of substitution". Bash Reference Manual

$(somecommand)

is preferrable. Also, something like:

name=$(echo "$inputname" | /usr/bin/tr '[:upper:]' '[:lower:]')

is preferable for transforming character classes. Good luck!