Home > Net >  Bash script - How to preserve new line character passed to bash function?
Bash script - How to preserve new line character passed to bash function?

Time:02-11

I have two files:

touch a.txt
touch b.txt

In bash I would like to list them each one in its own line.

#!/bin/bash
var=$(ls -1 *.txt)
echo "$var"

Because there are double quotes in: echo "$var" command each of file is displayed in separate lines (that is what I want):

a.txt
b.txt

Now to the problem. If I add function:

#!/bin/bash
function fun_cmd () {
     $1
}
var=$(ls -1 *.txt)
fun_cmd "echo $var"

and echo command displays them in one single line:

a.txt b.txt

In the last sample (function), I would like output to be displayed in two lines, just like first sample.

CodePudding user response:

  • Always quote correctly!
  • Don't use a single argument, but all argument of your function with "$@"
#!/usr/bin/env bash
function fun_cmd () {
     "$@"
}
var="$(ls -1 -- *txt)"
fun_cmd echo "$var"
  • Related