Eco nueva línea en impresiones Bash literal
En Bash, probé esto:
echo -e "hello\nworld"
Pero no imprime una nueva línea, solo \n
. ¿Cómo puedo hacer que imprima la nueva línea?
Estoy usando Ubuntu 11.04.
17 answers
Podrías usar printf
en su lugar:
printf "hello\nworld\n"
printf
tiene un comportamiento más consistente que echo
. El comportamiento de echo
varía mucho entre las diferentes versiones.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-20 14:46:18
¿Estás seguro de que estás en bash? Funciona para mí, las tres maneras:
echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-14 21:38:01
echo $'hello\nworld'
Imprime
hello
world
$''
las cadenas usan ANSI C Citando :
Las palabras de la forma
$'string'
son tratadas especialmente. La palabra se expande a cadena, con caracteres de escape de barra invertida reemplazados como se especifica en el estándar ANSI C.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-12 15:19:47
Siempre podrías hacer echo ""
.
Por ejemplo
echo "Hello"
echo ""
echo "World"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-07 11:12:13
En la remota posibilidad de que alguien se encuentre golpeando la cabeza contra la pared tratando de averiguar por qué el guion de un compañero de trabajo no imprimirá nuevas líneas, tenga cuidado con esto - >
#!/bin/bash
function GET_RECORDS()
{
echo -e "starting\n the process";
}
echo $(GET_RECORDS);
Como en lo anterior, la ejecución real del método puede estar envuelta en un eco que reemplaza cualquier eco que pueda estar en el propio método. Obviamente diluí esto por brevedad, ¡no fue tan fácil de detectar!
Entonces puede informar a sus camaradas que una mejor manera de ejecutar funciones sería así:
#!/bin/bash
function GET_RECORDS()
{
echo -e "starting\n the process";
}
GET_RECORDS;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-08 20:15:15
Intenta
echo -e "hello\nworld"
hello
world
Funcionó para mí en nano editor.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-05 11:06:59
Esto funciona para mí en raspbian,
echo -e "hello\\nworld"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-19 19:05:14
str='hello\nworld'
$ echo | sed "i$str"
hello
world
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-23 11:10:37
POSIX 7 sobre echo
Http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html
-e
no está definido y las barras invertidas están definidas por la implementación:
Si el primer operando es-n, o si alguno de los operandos contiene un carácter
, los resultados están definidos por la implementación.
A menos que tenga una extensión XSI opcional.
Así que use printf
en su lugar:
El operando de formato será se utiliza como la cadena de formato descrita en la Notación de Formato de archivo XBD [...]
La Notación del Formato de archivo :
\n
Mueva la posición de impresión al comienzo de la siguiente línea.
También tenga en cuenta que Ubuntu 15.10 y la mayoría de las distribuciones implementan echo
tanto como:
- un Bash incorporado:
help echo
- un ejecutable independiente:
which echo
Que puede llevar a cierta confusión.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-22 13:23:40
Una entrada más aquí para aquellos que no lo hicieron funcionar con ninguna de estas soluciones, y necesitan obtener un valor devuelto de su función:
function foo()
{
local v="Dimi";
local s="";
.....
s+="Some message here $v $1\n"
.....
echo $s
}
r=$(foo "my message");
echo -e $r;
Solo este truco funcionó en un linux en el que estaba trabajando con este bash:
GNU bash, version 2.2.25(1)-release (x86_64-redhat-linux-gnu)
Espero que ayude a alguien con un problema similar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-31 14:20:48
Mi guión:
echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings
Salida:
WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:
En mi guión bash me estaba enojando como tú hasta que acabo de intentarlo:
echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"
Simplemente presione enter donde desea insertar ese salto. La salida ahora es:
WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-14 08:58:12
También puedes usar echo con llaves,
$ (echo hello; echo world)
hello
world
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-05 09:32:48
Esto podría hacerse mejor como
x="\n"
echo -ne $x
- la opción e interpretará las barras invertidas para la secuencia de escape
- n opción eliminará la nueva línea final en la salida
PD: el comando echo tiene el efecto de incluir siempre una nueva línea final en la salida, por lo que se requiere-n para desactivar esa cosa (y hacerla menos confusa)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-30 07:06:02
También puedes hacer:
echo "hello
world"
Esto funciona para mí en mi macOS.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-31 16:45:37
A veces puede pasar varias cadenas separadas por un espacio y se interpretará como \n
.
Por ejemplo, cuando se utiliza un script de shell para notificaciones multilínea:
#!/bin/bash
notify-send 'notification success' 'another line' 'time now '`date +"%s"`
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-26 07:37:43
Hay un nuevo expansión de parámetros añadida en bash 4.4
que interpreta secuencias de escape:
${parameter@operator} - E operator
La expansión es una cadena que es el valor del parámetro con secuencias de escape de barra invertida expandidas como con la cita
$'…'
mecanismo.
$ foo='hello\nworld'
$ echo "${foo@E}"
hello
world
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 20:25:04
Funciona para mí en CentOS:
echo -e ""hello\nworld""
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-27 08:48:33