Dynamic variable names in Bash

后端 未结 14 1995
清酒与你
清酒与你 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

    I want to be able to create a variable name containing the first argument of the command

    script.sh file:

    #!/usr/bin/env bash
    function grep_search() {
      eval $1=$(ls | tail -1)
    }
    

    Test:

    $ source script.sh
    $ grep_search open_box
    $ echo $open_box
    script.sh
    

    As per help eval:

    Execute arguments as a shell command.


    You may also use Bash ${!var} indirect expansion, as already mentioned, however it doesn't support retrieving of array indices.


    For further read or examples, check BashFAQ/006 about Indirection.

    We are not aware of any trick that can duplicate that functionality in POSIX or Bourne shells without eval, which can be difficult to do securely. So, consider this a use at your own risk hack.

    However, you should re-consider using indirection as per the following notes.

    Normally, in bash scripting, you won't need indirect references at all. Generally, people look at this for a solution when they don't understand or know about Bash Arrays or haven't fully considered other Bash features such as functions.

    Putting variable names or any other bash syntax inside parameters is frequently done incorrectly and in inappropriate situations to solve problems that have better solutions. It violates the separation between code and data, and as such puts you on a slippery slope toward bugs and security issues. Indirection can make your code less transparent and harder to follow.

提交回复
热议问题