Home > Blockchain >  Defining shell variables inside IF block [duplicate]
Defining shell variables inside IF block [duplicate]

Time:09-21

I'm trying to set a variable's value based on a condition. So I've written an IF block. My code example:

read -p "vHost/Domain Name *[www.example.com]: "  hostName;

if [ ${#hostName} -gt 0 ] ; 
    then
        read -p "Document Root [/var/www/]: " documentRootInput

        if [ ${#documentRootInput} -gt 0 ] ;
            then
                documentRoot = "${documentRootInput}/${hostName}";
            else
                documentRoot = "/var/www/${hostName}";
        fi

        echo $documentRoot

    else
        echo $'\e[1;31m'Invaild Host Name$'\e[0m'
fi

when I execute this, i get the following error:

./test.sh: line 29: documentRoot: command not found

What is the proper procedure to define variables inside an IF block?

Or, if there any ternary operator in shell so that I can set the value of a variable based on a logic?

CodePudding user response:

Attempted assignments like:

something = "something/else"

should not have a spaces around the =. That's because bash treats this as trying to run the something program, giving it the two arguments = and something/else.

Instead, use:

something="something/else"

And, if you value brevity in your code, you could opt for the shorter:

read -p "Document Root [/var/www/]: " docRootInput
[[ -z "${docRootInput}" ]] && docRootInput=/var/www/"
documentRoot="${docRootInput}/${hostName}"

You'll see I've changed hostname into hostName there as well. You use both in your code so I'm not sure which is the correct one, but I reasonably certain there'll only be one correct one, whichever that is :-)

  • Related