Add prefix and suffix to $@ in bash

后端 未结 3 1174
孤街浪徒
孤街浪徒 2020-12-16 15:13

How to add suffix and prefix to $@?

If I do $PREFIX/$@/$SUFFIX, I get the prefix and the suffix only in the first parameter.

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 16:15

    Note: This is essentially a slightly more detailed version of sjam's answer.

    John1024's answer is helpful, but:

    • requires a subshell (which involves a child process)
    • can result in unwanted globbing applied to the array elements.

    Fortunately, Bash parameter expansion can be applied to arrays too, which avoids these issues:

    set -- 'one' 'two' # sample input array, which will be reflected in $@
    
    # Copy $@ to new array ${a[@]}, adding a prefix to each element.
    # `/#` replaces the string that follows, up to the next `/`,
    # at the *start* of each element.
    # In the absence of a string, the replacement string following
    # the second `/` is unconditionally placed *before* each element.
    a=( "${@/#/PREFIX}" )
    
    # Add a suffix to each element of the resulting array ${a[@]}.
    # `/%` replaces the string that follows, up to the next `/`,
    # at the *end* of each element.
    # In the absence of a string, the replacement string following
    # the second `/` is unconditionally placed *after* each element.
    a=( "${a[@]/%/SUFFIX}" )
    
    # Print the resulting array.
    declare -p a
    

    This yields:

    declare -a a='([0]="PREFIXoneSUFFIX" [1]="PREFIXtwoSUFFIX")'
    

    Note that double-quoting the array references is crucial to protect their elements from potential word-splitting and globbing (filename expansion) - both of which are instances of shell expansions.

提交回复
热议问题