How do quotes handle script arguments?

Quotes in shell scripting play a crucial role in how arguments are handled, especially when dealing with spaces and special characters. Here's how they work:

  1. Double Quotes ("):

    • When you enclose an argument in double quotes, the shell treats everything inside the quotes as a single argument, preserving spaces and special characters.
    • Variables inside double quotes are expanded.

    Example:

    ./script.sh "Hello World" "This is a test"

    In this case, the script receives two arguments: Hello World and This is a test.

  2. Single Quotes ('):

    • Single quotes prevent any variable expansion or interpretation of special characters. Everything inside single quotes is treated literally.

    Example:

    ./script.sh 'Hello World' 'This is a test'

    Here, the script also receives two arguments: Hello World and This is a test, but if you had a variable inside single quotes, it would not be expanded.

  3. No Quotes:

    • If you do not use quotes and the argument contains spaces, the shell will treat each space-separated word as a separate argument.

    Example:

    ./script.sh Hello World This is a test

    In this case, the script receives five separate arguments: Hello, World, This, is, and a, test.

Summary

  • Use double quotes to preserve spaces and allow variable expansion.
  • Use single quotes to preserve the literal value of the argument without expansion.
  • Avoid quotes if you want to split the input into separate arguments based on spaces.

0 Comments

no data
Be the first to share your comment!