diff --git a/oil_lang/testdata/array-rewrite-1.sh b/oil_lang/testdata/array-rewrite-1.sh new file mode 100644 index 0000000000..90b4d2125b --- /dev/null +++ b/oil_lang/testdata/array-rewrite-1.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# +# Example of Oil arrays. +# +# Adapted from ./linux-4.8.7/scripts/tags.sh + +# Show args to a command +argv() { spec/bin/argv.py "$@"; } + +# +# OLD, BASH-COMPATIBLE WAY +# + +regex=('one' 'two') +flags=() + +for r in "${regex[@]}"; do + flags[${#flags[@]}]="--regex=$r" +done + +argv "${flags[@]}" + + +# +# NEW OIL WAY +# +# Things fixed: +# - verbose "${a[@]}" becomes @a +# - a=() is weird because it doesn't allow spaces around = +# - builtin 'push' for appending +# + +shopt -s static-word-eval oil-parse-at + +var regex2 = @(two three) +var flags2 = @() + +for r in @regex2; do + push flags2 _ "--regex=$r" +done + +argv @flags2 diff --git a/oil_lang/testdata/array-rewrite-2.sh b/oil_lang/testdata/array-rewrite-2.sh new file mode 100644 index 0000000000..220ca92880 --- /dev/null +++ b/oil_lang/testdata/array-rewrite-2.sh @@ -0,0 +1,55 @@ +#!/bin/bash +# +# Example of rewriting string-based argv processing to use arrays. +# +# Adapted from ./linux-4.8.7/scripts/link-vmlinux.sh + +# Show args to a command +argv() { spec/bin/argv.py "$@"; } + +# +# OLD, BASH-COMPATIBLE WAY +# +# This style can't handle paths with spaces + +path='/etc/path with spaces' + +CONFIG_HAVE_FOO=yes + +flags='' + +if [ -n "${CONFIG_HAVE_FOO}" ]; then + flags="${flags} --foo=$path" +fi + +if [ -n "${CONFIG_HAVE_BAR}" ]; then + flags="${flags} --bar" +fi + +argv ${flags} # unquoted splitting + + +# +# NEW OIL WAY +# +# - no quoting is necessary because of static-word-eval +# - splice arrays with @ +# - builtin 'push' for appending +# - I might want to change the ignored delimiter character _ to something like +# : or :: or \\ . Opinions? + +shopt -s oil-parse-at static-word-eval + +CONFIG_HAVE_FOO=yes + +var flags = @() + +if test -n $CONFIG_HAVE_FOO; then + push flags _ --foo=$path +fi + +if test -n $CONFIG_KALLSYMS_BASE_RELATIVE; then + push flags _ --bar +fi + +argv @flags