Skip to content

Instantly share code, notes, and snippets.

@klaufir216
Last active August 4, 2019 16:09
Show Gist options
  • Select an option

  • Save klaufir216/70af9b5d457236b3e83d0b803b4eb007 to your computer and use it in GitHub Desktop.

Select an option

Save klaufir216/70af9b5d457236b3e83d0b803b4eb007 to your computer and use it in GitHub Desktop.
Bash: always quote when forwarding parameters: "$@"

Bash: always quote when forwarding parameters: "$@"

Create dumpargs executable for testing purposes

cat <<//EOF >dumpargs.c
#include <stdio.h>

int main(int argc, char *argv[]) {
  int i;
  for(i = 0; i < argc; ++i)
    printf("[%d] '%s'\n", i, argv[i]);
  return 0;
}
//EOF

gcc dumpargs.c -o dumpargs

Example: dumpargs will dump all arguments

$ ./dumpargs 1 2 3
[0] './dumpargs'
[1] '1'
[2] '2'
[3] '3'

Bash: Passing parameters without quoting (DONT DO THIS)

cat <<EOF >testargs1.sh
#!/bin/bash
./dumpargs $@
EOF
chmod +x ./testargs1.sh

Dumping parameters

$ ./testargs1.sh "1 2 3" "4 5 6"
[0] './dumpargs'
[1] '1'
[2] '2'
[3] '3'
[4] '4'
[5] '5'
[6] '6'

Even though ./testargs1.sh got two parameters, dumpargs received 6 params space-separated.

Bash: Passing parameters with quoting

cat <<EOF >testargs2.sh
#!/bin/bash
./dumpargs "$@"
EOF
chmod +x ./testargs2.sh
$ ./testargs2.sh "1 2 3" "4 5 6"
[0] './dumpargs'
[1] '1 2 3'
[2] '4 5 6'

Now the parameters do not get space separated when forwarded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment