Skip to content

Instantly share code, notes, and snippets.

@FilipDominec
Last active July 27, 2016 13:23
Show Gist options
  • Save FilipDominec/62e6b09efbea79b9ad66 to your computer and use it in GitHub Desktop.
Save FilipDominec/62e6b09efbea79b9ad66 to your computer and use it in GitHub Desktop.
par=(so "me thin" g); command "${par[@]}" ... to run a bash command with multiple parameters possibly containing spaces, all stored in a single variable, you must write it as
#!/bin/bash
fn_bash() { for x in "$@"; do echo $x; done; }
echo '#!/usr/bin/env python' > printer.py
echo 'import sys ' >> printer.py
echo 'for a in sys.argv: print a' >> printer.py
chmod +x printer.py
fn() { ./printer.py "$@" ; }
echo 'Example 1 supplies the arguments at the line of function call and prints 3 lines, as we need'
fn a "b c" d
echo 'But what if we wish to pass these arguments through a variable?'
echo -e 'TExample 2 is wrong since it prints 4 lines: '
par="a 'b c' d"
fn ${par}
echo -e '\n\nExample 3: by adding parentheses, we get only one line:'
par="a 'b c' d"
fn "${par}"
echo -e '\n\nExample 4, by somewhat arcane way we get the CORRECT RESULT:'
par=(a "b c" d)
fn "${par[@]}"
@FilipDominec
Copy link
Author

FilipDominec commented Jul 27, 2016

To use the same functionality from the bash command line, just access the user-supplied parameters by "${@}" in your script. In this case you do not have to care about the somewhat quirky function-calling syntax.

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