Question

I'd like to print a \ after each line in a bash script.

Example: the output of $k is:

git-core
nano
apache2

Now I want to install this packages using apt. The only solution I now is:

sudo apt-get install git-core \
nano \
apache2

how do I add this character?

Was it helpful?

Solution

As suggested, you may be looking at the wrong solution for your problem.

You can replace the new line characters from $k with spaces:

k=$(echo "$k" | tr '\n' ' ')

Better yet, you can take advantage of the bash word parsing, knowing that apt package names don't have spaces in their names (and assuming you are sure all that $k contains are package names, separated by newline):

sudo apt-get install $k

The lack of quoting for $k will make bash re-parse the newlines into regular word separators (spaces).

If, for some other reason, you really really want to add backslash to the end of each line, you can always use sed:

echo "$k" | sed 's/$/\\/'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top