How do i use double quotes in a bash shell script within single square brackets?



  • This is an example of a shell script that uses double quotes.

    $ cat quotethis.sh
    Myfile="Juicy apples"
    [ -r $Myfile -a -f $Myfile ] && cat $Myfile
    

    Running this scripts

    $ ./quotethis.sh 
    ./quotethis.sh 
    ./quotethis.sh: line 2: test: too many arguments
    

    It is better to demonstrate the error first, the shell script thinks I passed it two file names, one called Juicy and one called apples. The double quote preserved the space in between them.

    We need to make it look like just one name called Juicy apples because that's the name of our file; we do this by putting double quotes when calling the variable, like this:

    $ cat quotethis.sh
    Myfile="Juicy apples"
    [ -r "$Myfile" -a -f "$Myfile" ] && cat "$Myfile"
    

    Running this script. Displays the file ok.

    $ ./quotethis.sh
    This is my super juicy apple!
    

    When you assign a variable, such as Fruit below, and use it elsewhere in the script, for example in an echo command, bash perform parameter expansion. In cases like this, it's best to double quote the entire echo message, then when it prints the Fruits it preserves the spaces.

    Fruits="apples oranges pears"
    echo "These are the fruits I will be eating today $Fruit"
    

    Note: Something to take into consideration is the use of double square brackets for testing conditions and use of double quotes within them is different.

    Within double square brackets, the double quotes with them are optional.


Log in to reply
 

© Lightnetics 2024