keelar
keelar

Reputation: 6026

Concatenate strings in multiple lines using bash

Given a list of arguments, I am trying to produce a string looks like the following using bash script:

 - arg_1
 - arg_2
 - arg_3
 - arg_4

And here is my script trying to do this:

seeds=
for i in $*; do
  seeds=`printf "$seeds    - $i\n"`
done;
echo "$seeds"

However, when I run it with input arg_1 arg_2 arg_3 arg_4, the above script generates the following output, which apparently ignores my spacing and new-line character:

- arg_1 - arg_2 - arg_3 - arg_4

Can I know what did I do wrong in my script? or is there a better way to do this?

Upvotes: 1

Views: 9445

Answers (3)

that other guy
that other guy

Reputation: 123680

Like sudo_O says (and ShellCheck would have pointed out), you should use "$@" rather than $* for the minimal fix.

You asked if there was a better way of doing it, though, and there definitely is. When given more arguments than necessary to fulfill the format string, printf will repeat the output as necessary. This lets us simply write:

printf "- %s\n" "$@" 

Upvotes: 3

Chris Seymour
Chris Seymour

Reputation: 85883

Quoting and whitespace is very important in the shell:

#!/usr/bin/env bash

for arg in "$@"; do
    seed="$seed    - $arg\n"
done
echo -ne "$seed"

Demo:

$ ./script.sh arg_1 arg_2 arg_3 arg_4
    - arg_1
    - arg_2
    - arg_3
    - arg_4

Upvotes: 5

user1146332
user1146332

Reputation: 2770

I think your script is too complex. I don't think you need command substitution here. May you try this one

seeds=
for i in $*; do
  seeds="$seeds\n- $i"
done;
echo -e ${seeds#\\n}

Upvotes: 1

Related Questions