1

This-

$a=`ls` | do something | etc. | etc. | etc...
echo "$a"

gives this-

file1
file2
file3

But I want to append something to the end of that variable, so I tried

a=${a}\nfile4

But I get this-

file1
file2
file3nfile4   # wrong!
  • 2
    can you try with echo : a=$(echo -e "${a}\nfile") – msp9011 Jun 11 '18 at 11:10
  • @SivaPrasath WORKS! Pls add as answer so I can accept it? – lonix Jun 11 '18 at 11:21
  • in a more general note, you should use $() instead of `` – Kiwy Jun 11 '18 at 11:41
  • @Kiwy why is that? – lonix Jun 11 '18 at 15:20
3

In Bash, you can append to a variable using var+=value. But your problem isn't that, but in generating the newline. The easiest way is to use $'..' quoting, which interprets backslash-escapes like \n for newline:

a+=$'\nfile4'
1

can you try with echo :

a=$(echo -e "${a}\nfile")
1

If all you want to do is to get the listing of files in the current directory and then append a string to each of these names:

set -- *
printf '%s-somestring\n' "$@"

or, using a bash array,

names=( * )
printf '%s-somestring\n' "${names[@]}"

Using an array, either the array of positional parameters (the first example above, which will work in all POSIX shells), or a bash array, is the safest way to work with filenames. If you are converting the filenames into some sort of delimited string, then you will run into issues when you have filenames containing whatever character you have chosen to delimit the string with.

To only append something to the end of the output, do that in a separate echo:

# code that output something
# then,
echo 'additional data'

Or, modifying my examples from above:

set -- * 'additional data'
printf '%s\n' "$@"

and

names=( * 'additional data' )
printf '%s\n' "${names[@]}"

Or...

set -- *
set -- "$@" 'additional data'
printf '%s\n' "$@"

and

names=( * )
names+=( 'additional data' )
printf '%s\n' "${names[@]}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.