Dynamic variable names in Bash

后端 未结 14 1996
清酒与你
清酒与你 2020-11-21 05:38

I am confused about a bash script.

I have the following code:

function grep_search() {
    magic_way_to_define_magic_variable_$1=`ls | tail -1`
    e         


        
14条回答
  •  爱一瞬间的悲伤
    2020-11-21 06:18

    Use declare

    There is no need on using prefixes like on other answers, neither arrays. Use just declare, double quotes, and parameter expansion.

    I often use the following trick to parse argument lists contanining one to n arguments formatted as key=value otherkey=othervalue etc=etc, Like:

    # brace expansion just to exemplify
    for variable in {one=foo,two=bar,ninja=tip}
    do
      declare "${variable%=*}=${variable#*=}"
    done
    echo $one $two $ninja 
    # foo bar tip
    

    But expanding the argv list like

    for v in "$@"; do declare "${v%=*}=${v#*=}"; done
    

    Extra tips

    # parse argv's leading key=value parameters
    for v in "$@"; do
      case "$v" in ?*=?*) declare "${v%=*}=${v#*=}";; *) break;; esac
    done
    # consume argv's leading key=value parameters
    while (( $# )); do
      case "$v" in ?*=?*) declare "${v%=*}=${v#*=}";; *) break;; esac
      shift
    done
    

提交回复
热议问题