please explain why this ksh echo deletes character

Please explain why this works. Am unable to find another definition for the '%', which would explain this behaviour:

spaceLeft=`df -h /myPartition | tail -1`
# output looks like:   /dev/sda5              10G  1.2G   12G  29% /

set -- $space

#this deletes the trailing '%' sign, which is what is needed, but wondering how?
# can someone better explain this statement for me :-)
$(echo ${5%\%})

# prints 29

The set command parse's the contents of $spaceLeft and places each component into $1 $2 $3 $4 $5 respectively.

The 5 is referring to $5. The command is checking the last character of the contents of $5 for a % sign (protected as \%) and deleting that character.

It is explained in the "man" page for your Shell in the section about:

Notice that the first percentage sign % is part of the syntax of the command which is why the percentage sign we are looking for is escaped as \% .

It's a string operation:

${string%substring} = Strip shortest match of $substring from back of $string

In your case the backslash takes away the special meaning of the percent sign, so it says strip off the percent sign.

Actually your code:

$(echo ${5%\%})

will try to run a command called "29". I think you don't want the $( ) syntax around your echo statement?

I think O/P meant something like:

percentage=$(echo ${5%\%})
echo "${percentage}"

Save a process, no need to run echo (unless there is more to the story that has been edited out for example purposes)

percentage=${5%\%}
2 Likes

Thank you, question answered. I was not aware of the variable substitution offered by ${var%pattern}

In "man ksh" it's in the section headed "Parameter Substitution".

1 Like