LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Why use ${REPLY:0:1} and not $REPLY (https://www.linuxquestions.org/questions/linux-newbie-8/why-use-%24%7Breply-0-1%7D-and-not-%24reply-4175452798/)

Batistuta_g_2000 03-05-2013 10:04 AM

Why use ${REPLY:0:1} and not $REPLY
 
What are the semicolon values for - is it to shift values?

Code:

echo -e "Do you wish to restore all these file(s)/directory(ies)? [Enter Y to restore all; N to choose single file]: \c"
        read
        if [[ ${REPLY:0:1} = y ]] || [[ ${REPLY:0:1} = Y ]]; then


shivaa 03-05-2013 10:08 AM

To me, it's look like 'getopts' command line aguments. Can you post full script?

suicidaleggroll 03-05-2013 10:23 AM

That's how you extract a substring from a string in BASH

http://tldp.org/LDP/abs/html/refcards.html#AEN22664

All they're doing is extracting the first character from whatever the user entered and checking if it's a y or Y.

michaelk 03-05-2013 10:28 AM

Quote:

${REPLY:0:1}
It is a substring function of the form ${string:position:length}. The first character position of a string is 0. Just some error checking.

David the H. 03-05-2013 11:52 AM

BTW, the above could be made much cleaner. At the very least the two separate pattern matches can be combined into one: You can also fix it to match the first character directly instead of using the parameter substitution to extract it first.

Code:

if [[ ${REPLY:0:1} = [yY] ]]; then

if [[ $REPLY = [yY]* ]]; then

if [[ ${REPLY,,} = y* ]]; then
if [[ ${REPLY^^} = Y* ]]; then

But also, this kind of pattern match should usually be done with a case statement instead. It's nearly always faster, cleaner and more efficient than an if/test construct, and you can included as many conditions as you want.

Code:

case ${REPLY,,} in
    y*) echo "you selected yes" ;;
    n*) echo "you selected no"  ;;
    *) echo "what the heck is that?" ;;
esac



All times are GMT -5. The time now is 06:25 AM.