How do i set a default value to a variable in bash shell scripts?



  • It is handy to set a variable at times when one is not set, for instance, if you need to have a default number or string.

    The answer=${answer-"No"} in the script below is the code that sets the default. When anything other than Yes or No is entered, the variable answer is set to "No"

    The script looks like this:

    echo -n "Would you like to turn on syntax highlighting? Yes/No (Default: No): "
    read answer
    case $answer in
    No|no)
       echo "Syntax highlighting disabled"
       ;;
    Yes|yes)
       echo "Syntax highlighting enabled"
       ;;
    *) answer=${answer-"No"}
       echo "Selected default - Syntax highlighting disabled"
       ;;
    esac
    

    Running the script.

    $ ./myscript
    Would you like to turn on syntax highlighting? Yes/No (Default: No): 
    Selected default - Syntax highlighting disabled
    
    $ ./myscript
    Would you like to turn on syntax hightlighting? Yes/No (Default: No): No
    Syntax highlighting disabled
    
    $ ./myscript
    Would you like to turn on syntax hightlighting? Yes/No (Default: No): Yes
    Syntax highlighting enabled
    

Log in to reply
 

© Lightnetics 2024