Skip to content

Instantly share code, notes, and snippets.

@akanix42
Created August 24, 2020 18:47
Show Gist options
  • Save akanix42/c8f80a5fbfa6ac131572bf627856ead6 to your computer and use it in GitHub Desktop.
Save akanix42/c8f80a5fbfa6ac131572bf627856ead6 to your computer and use it in GitHub Desktop.
Bash array expansion as command parameters
#!/usr/bin/env bash
((BASH_VERSINFO > 3)) || {
echo 'Requires Bash 4+'
exit
}
set -ux
echo foo 1 | tail "${tail_args[@]}"
# Result: Unbound variable, as expected
#-----
tail_args= # Empty variable
echo foo 2 | tail "${tail_args[@]}"
# Result: Errors, because this is equivalent to the following command:
echo foo 3 | tail ""
#-----
echo foo 4 | tail "${tail_args[@]:+"${tail_args[@]}"}"
# Result: Succeeds without passing the arguments, because this is equivalent to:
if [[ -n "${tail_args[*]}" ]]; then
echo foo 5 | tail "${tail_args[@]}"
else
echo foo 6 | tail
fi
tail_args=(-n 1)
echo foo 7 | tail "${tail_args[@]}"
echo foo 8 | tail "${tail_args[@]:+"${tail_args[@]}"}"
#----- No difference when the variable isn't empty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment