BASH   10

array demo sh

Guest on 13th May 2022 01:38:52 AM

  1. #!/bin/bash
  2. #
  3. # Usage:
  4. #   ./array-demo.sh
  5.  
  6. set -o nounset
  7. set -o pipefail
  8. set -o errexit
  9.  
  10. args() {
  11.   python -c 'import sys; print sys.argv[1:]' "$@"
  12. }
  13.  
  14. show-b() {
  15.   args "${b[@]}"
  16. }
  17.  
  18. array-demo() {
  19.   a=('Track 01.mp3' 'Track 02.mp3')
  20.  
  21.   # Here are 4 incorrect ways to pass an array to a command, and one correct
  22.   # way, using 8 chars.
  23.  
  24.   echo RESULTS OF BAD WAYS TO PASS AN ARRAY
  25.   echo
  26.   args ${a}   # only gives the first item
  27.   args ${a[*]}
  28.   args "${a[*]}"
  29.   args ${a[@]}
  30.   echo
  31.   echo -n 'GOOD WAY is "${a[@]}"  ->  '
  32.   args "${a[@]}"  # Using it correctly takes 8 chars
  33.  
  34.   echo
  35.   echo RESULTS OF BAD WAYS TO COPY AN ARRAY
  36.   echo
  37.  
  38.   # Here are 8 incorrect ways to copy an array, and 1 correct way, using 10
  39.   # extra characters besides the name of the array.
  40.  
  41.   b=$a
  42.   show-b  # only gives the first item
  43.  
  44.   b=${a[*]}
  45.   show-b
  46.  
  47.   b="${a[*]}"
  48.   show-b
  49.  
  50.   b=${a[@]}
  51.   show-b
  52.  
  53.   b="${a[@]}"  # Doesn't work!
  54.   show-b
  55.  
  56.   b=( $a )
  57.   show-b
  58.  
  59.   b=( ${a[*]} )
  60.   show-b
  61.  
  62.   b=( "${a[*]}" )
  63.   show-b
  64.  
  65.   b=( ${a[@]} )
  66.   show-b
  67.  
  68.   b=( "${a[@]}" )  # Copying it correctly takes 10 chars.  You need to
  69.                    # SPLICE the old array into a new array.
  70.   echo
  71.   echo -n 'GOOD WAY is b=( "${a[@}}" )  ->  '
  72.   show-b
  73.   echo
  74. }
  75.  
  76. array-demo "$@"

Raw Paste


Login or Register to edit or fork this paste. It's free.