【问题标题】:a single variable acting as multiple parameters in bash?a single variable acting as multiple parameters in bash?
【发布时间】:2022-12-01 20:18:27
【问题描述】:

How to split a single variable into multiple arguments?

In fish shell, one can use

set my_var (echo 'line1
line2
line3' | string split '\n')

./my_command $my_var

this is equivalent to

./my_command line1 line2 line3

so a single variable acting as multiple parameters, how to do that in bash shell?

【问题讨论】:

    标签: bash


    【解决方案1】:

    If arguments are separated by newlines:

    #!/bin/bash
    
    my_var='line1
    line2
    line3'
    
    mapfile -t args <<< "$my_var"
    ./my_command "${args[@]}"
    

    args is an array name here (it can be any other valid name). "${args[@]}" expands array elements as a list.

    【讨论】:

      【解决方案2】:

      You could try mapfile, something like:

      #!/usr/bin/env bash
      
      my_var="line1 line2 line3"
      
      mapfile -t argv <<< "${my_var/ //$'
      '}"
      
      ./my_command "${argv[@]}"
      

      If the variable has embedded newlines, try

      #!/usr/bin/env bash
      
      my_var='line1
      line2
      line3'
      
      mapfile -t argv <<< "$my_var"
      

      【讨论】:

        【解决方案3】:

        Of course, many times you don't need an array at all. If you don't need to iterate over the tokens multiple times or compare them to the adjacent ones or etc, just loop directly.

        while read -r value; do
            : something with "$value"
        done <<____HERE
            first value
            second one
            third goes here
        ____HERE
        

        【讨论】:

          猜你喜欢
          • 2016-12-04
          • 1970-01-01
          • 2022-12-02
          • 2022-12-02
          • 2022-12-26
          • 2020-08-06
          • 2022-12-27
          • 2022-12-28
          • 2022-12-02
          相关资源
          最近更新 更多