Comentando en un guión Bash
¿Cómo puedo comentar cada línea de las siguientes líneas de un script?
cat ${MYSQLDUMP} | \
sed '1d' | \
tr ",;" "\n" | \
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' | \
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' | \
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' | \
tr "\n" "," | \
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | \
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}
Si intento agregar un comentario diciendo " cat cat {MYSQLDUMP} / \ # Output MYSQLDUMP File", obtengo:
Suprimir: no encontrado
¿Es posible comentar aquí o no debido a "| \
"?
6 answers
Esto tendrá algunos gastos generales, pero técnicamente responde a su pregunta:
echo abc `#Put your comment here` \
def `#Another chance for a comment` \
xyz, etc.
Y para las tuberías específicamente, hay una solución limpia sin sobrecarga:
echo abc | # Normal comment OK here
tr a-z A-Z | # Another normal comment OK here
sort | # The pipelines are automatically continued
uniq # Final comment
Consulte la pregunta de desbordamiento de pilaCómo Poner Comentario de Línea para un Comando Multilínea.
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-06 14:57:04
La barra invertida final debe ser el último carácter de la línea para que se interprete como una orden de continuación. No se permiten comentarios o incluso espacios en blanco después de él.
Deberías poder poner líneas de comentarios entre tus comandos
# output MYSQLDUMP file
cat ${MYSQLDUMP} | \
# simplify the line
sed '/created_at/d' | \
# create some newlines
tr ",;" "\n" | \
# use some sed magic
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' | \
# more magic
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' | \
# even more magic
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' | \
tr "\n" "," | \
# I hate phone numbers in my output
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | \
# one more sed call and then send it to the CSV file
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}
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
2009-09-21 18:29:12
Como señaló DigitalRoss, la barra invertida final no es necesaria cuando la línea termina en |
. Y puedes poner comentarios en una línea que sigue a |
:
cat ${MYSQLDUMP} | # Output MYSQLDUMP file
sed '1d' | # skip the top line
tr ",;" "\n" |
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' |
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' |
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' |
tr "\n" "," |
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | # hate phone numbers
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}
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
2009-09-21 18:48:47
La barra invertida escapa al #, interpretándolo como su carácter literal en lugar de un carácter de comentario.
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
2009-09-21 18:22:43
$IFS
hacks de comentarios
Este hack utiliza parámetro de expansión en $IFS
, que se utiliza para separar las palabras en los comandos:
$ echo foo${IFS}bar
foo bar
Del mismo modo:
$ echo foo${IFS#comment}bar
foo bar
Usando esto, puede poner un comentario en una línea de comandos con contination:
$ echo foo${IFS# Comment here} \
> bar
foo bar
Pero el comentario tendrá que estar antes de la continuación \
.
Tenga en cuenta que la expansión de parámetros se realiza dentro del comentario:
$ ls file
ls: cannot access 'file': No such file or directory
$ echo foo${IFS# This command will create file: $(touch file)}bar
foo bar
$ ls file
file
Raras excepción
El único caso raro que falla es si $IFS
previamente comenzó con el texto exacto que se elimina a través de la expansión (es decir, después del carácter #
):
$ IFS=x
$ echo foo${IFS#y}bar
foo bar
$ echo foo${IFS#x}bar
foobar
Tenga en cuenta que el final foobar
no tiene espacio, lo que ilustra el problema.
Dado que $IFS
solo contiene espacios en blanco por defecto, es extremadamente poco probable que se encuentre con este problema.
Crédito a @pjh comentario que provocó esta respuesta.
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-11-19 05:33:57
Aquí hay un script bash que combina las ideas y modismos de varios comentarios anteriores para proporcionar, con ejemplos, comentarios en línea que tienen la forma general ${__+ <comment text>}
.
En particular
-
<comment text>
puede ser multilínea -
<comment text>
no es un parámetro expandido - no se generan subprocesos (por lo que los comentarios son eficientes)
Hay una restricción en el <comment text>
, a saber, llaves desequilibradas '}'
y paréntesis ')'
deben ser protegidos (es decir, '\}'
y '\)'
).
Hay un requisito en el entorno local de bash:
- el nombre del parámetro
__
debe estar desactivado
Cualquier otro parámetro-nombre de bash válido sintácticamente servirá en lugar de __
, siempre que el nombre no tenga un valor establecido.
Un script de ejemplo sigue
# provide bash inline comments having the form
# <code> ${__+ <comment>} <code>
# <code> ${__+ <multiline
# comment>} <code>
# utility routines that obviate "useless use of cat"
function bashcat { printf '%s\n' "$(</dev/stdin)"; }
function scat { 1>&2 bashcat; exit 1; }
# ensure that '__' is unset && remains unset
[[ -z ${__+x} ]] && # if '__' is unset
declare -r __ || # then ensure that '__' remains unset
scat <<EOF # else exit with an error
Error: the parameter __='${__}' is set, hence the
comment-idiom '\${__+ <comment text>}' will fail
EOF
${__+ (example of inline comments)
------------------------------------------------
the following inline comment-idiom is supported
<code> ${__+ <comment>} <code>
<code> ${__+ <multiline
comment>} <code>
(advisory) the parameter '__' must NOT be set;
even the null declaration __='' will fail
(advisory) protect unbalanced delimiters \} and \)
(advisory) NO parameter-expansion of <comment>
(advisory) NO subprocesses are spawned
(advisory) a functionally equivalent idiom is
<code> `# <comment>` <code>
<code> `# <multiline
comment>` <code>
however each comment spawns a bash subprocess
that inelegantly requires ~1ms of computation
------------------------------------------------}
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-31 15:47:05