Question

I have the following script:

#!/bin/sh

echo "111\n111"
echo -e "222\n222"

Neither command works in both bash and dash:

$ /bin/dash test.sh 
111
111
-e 222
222
$ /bin/bash test.sh 
111\n111
222
222

Because I cannot be sure whether /bin/sh points to bash or dash, and I cannot be sure that /bin/bash or /bin/dash exists, this is a real problem. I also cannot split up the string and put a single "echo" for the newline because I need to pipe the string with newline into a command.

Is there any way to print a string with a newline that works in all shells?

Was it helpful?

Solution

printf should be more reliable:

$ printf "111\n111\n"
111
111

This should work the same way in both shells. Hopefully all shells.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top