Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Last active January 28, 2024 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryuheechul/3dcaaa51ed53e81f35c079ed55c5d84f to your computer and use it in GitHub Desktop.
Save ryuheechul/3dcaaa51ed53e81f35c079ed55c5d84f to your computer and use it in GitHub Desktop.

I actually didn't really know about the difference between $@ and "$@" until now.

I always had assumed that "$@" is not desirable thinking this would deliver argsments as just one.

Turns out that's not true and you can read about it from man bash.

@     Expands  to  the  positional  parameters,  starting from one.  In contexts where
       word splitting is performed, this expands each positional parameter to a separa
      te word; if not within double  quotes, these words  are  subject to word splitti
      ng.  In contexts where word splitting is not performed, this expands to a single
       word with each positional parameter separated by a space.  When the expansion o
      ccurs within double quotes, each parameter expands to a separate word.  That is,
       "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs withi
      n a word, the expansion of the  first  parameter  is  joined with  the  beginnin
      g  part of the original word, and the expansion of the last parameter is joined 
      with the last part of the original word.  When there are no positional parameter
      s, "$@"  and  $@  expand  to nothing (i.e., they are removed).

And you can easily test this

# desirable usage
$ cat <<EOF | bash -s - "single" "multiple chunk"
for i in "\$@"; do echo \$i; done
EOF
single
multiple chunk

# probably undesirable usage without quote
$ cat <<EOF | bash -s - "single" "multiple chunk"
for i in \$@; do echo \$i; done
EOF
single
multiple
chunk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment