Home > Mobile >  a single variable acting as multiple parameters in bash?
a single variable acting as multiple parameters in bash?

Time:12-01

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?

CodePudding user response:

You could try mapfile, something like:

#!/usr/bin/env bash

my_var="line1 line2 line3"

mapfile -t argv <<< "${my_var/ //$'\n'}"

./my_command "${argv[@]}"

If the variable has embedded newlines, try

#!/usr/bin/env bash

my_var='line1
line2
line3'

mapfile -t argv <<< "$my_var"

CodePudding user response:

Of course, many times you don't need a variable 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 over the values directly.

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

Or to adapt to your specific example

./my_command "line1" "line2" "line3"

or if you really need a loop,

for value in "line1" "line2" "line3"; do
    : something with "$value"
done

A variable you only interpolate once is often just a waste of memory. If it helps readability or configurability, it's a small price to pay; but many beginner scripts seem to be riddled with completely unnecessary variables.

CodePudding user response:

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). mapfile reads lines into the array (named args here). "${args[@]}" expands array elements as a list.

  •  Tags:  
  • bash
  • Related