Face it, backticks are a pain. BASH $() construct provides a simpler, more effective approach. This talk uses examples from automating git branches and command line processing with getopt(1) to show how $() works in shell scripts.
3. Commanding the shell
Think interpolating variables is fun?
Commands feel even better :-)
Extract command output into variables.
Control shell script execution.
25. Having options
getopt(1) shuffles command line args.
Leaves them suitable for iterating in code.
ARGS=$( getopt ... "$@" );
eval set -- "$ARGS”;
while :; do
case $1 in
’--’) shift; break;;
...
done;
26. Having options
getopt(1) shuffles command line args.
Leaves them suitable for iterating in code.
ARGS=$( getopt ... "$@" );
eval set -- "$ARGS”;
while :; do
case $1 in
’--’) shift; break;;
...
done;
27. Having options
eval + set
re-assign arguments.
ARGS=$( getopt ... "$@" );
eval set -- "$ARGS”;
while :; do
case $1 in
’--’) shift; break;;
...
done;
28. Having options
-- marks end of switches.
ARGS=$( getopt ... "$@" );
eval set -- "$ARGS”;
while :; do
case $1 in
’--’) shift; break;;
...
done;
29. Having options
Leave program args on the stack.
ARGS=$( getopt ... "$@" );
eval set -- "$ARGS”;
while :; do
case $1 in
’--’) shift; break;;
...
done;
30. Example: Glob vs. File Path
‘--file’ or ‘-f’ for a path.
‘--glob’ or ‘-g’ for a glob.
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help’
-n "$(basename $0)" -- "$@”
);
31. Example: Glob vs. File Path
-f & -g have args (f:g:).
-h & -? do not (h?).
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help'
-n "$(basename $0)" -- "$@”
);
32. Example: Glob vs. File Path
-f & -g have args (f:g:).
-h & -? do not (h?).
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help'
-n "$(basename $0)" -- "$@”
);
33. Example: Glob vs. File Path
-f & -g have options, -h & -? do not.
Long options are --file , --glob & --help.
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help'
-n "$(basename $0)" -- "$@”
);
34. Example: Glob vs. File Path
Errors use the executable basename.
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help'
-n "$(basename $0)" -- "$@”
);
35. Example: Glob vs. File Path
Errors use the executable basename.
With nested commands.
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help'
-n "$(basename $0)" -- "$@”
);
36. Example: Glob vs. File Path
Errors use the executable basename.
Without escapes, escaped escapes, doubled backticks...
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help'
-n "$(basename $0)" -- "$@”
);
37. Example: Glob vs. File Path
One more reason to use $(...).
ARGS=$(
getopt -o 'f:g:h?'
--long 'file:,glob:,help'
-n "$(basename $0)" -- "$@”
);