سؤال

I have a little problem with my bash script.

 #!/bin/bash
 ex xxx.html << "HERE"
 1,$s/\(foo\)/$1\1/
 wq
 HERE

This is just a little piece of my script. when I run it this is the output.

$1foo

Any way to fix this so the $1 will be the argument given to the script?

Thanks!

هل كانت مفيدة؟

المحلول

Try replacing "HERE" with HERE (unquoted). Also 1,$s becomes 1,\$s.

Here Documents
   This type of redirection instructs the shell to  read  input  from  the
   current source until a line containing only delimiter (with no trailing
   blanks) is seen.  All of the lines read up to that point are then  used
   as the standard input for a command.

   The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

   No  parameter expansion, command substitution, arithmetic expansion, or
   pathname expansion is performed on word.  If any characters in word are
   quoted,  the  delimiter is the result of quote removal on word, and the
   lines in the here-document are not expanded.  If word is unquoted,  all
   lines  of  the here-document are subjected to parameter expansion, com-
   mand substitution, and arithmetic expansion.  In the latter  case,  the
   character  sequence  \<newline> is ignored, and \ must be used to quote
   the characters \, $, and `.

   If the redirection operator is <<-, then all leading tab characters are
   stripped  from  input  lines  and  the line containing delimiter.  This
   allows here-documents within shell scripts to be indented in a  natural
   fashion.

Bash manual.

نصائح أخرى

Remplace "HERE" with HERE (without quotes) and remplace 1,$ with 1,\$ or %

You could write your script as follows:

#!/bin/bash
ex xxx.html <<-HERE
%s/foo/$1&/
x
HERE

Although you could also build a smaller script:

#!/bin/bash
sed -i "s/foo/$1&/g" xxx.html

Try this.

#!/bin/bash
(echo '1,$s/\(foo\)/'"$1"'\1/'; echo 'wq') | ex xxx.html

That's 1,$s/\(foo\)/ in single quotes, adjacent to $1 in double quotes (so the shell substitutes the parameter), adjacent to \1/ in single quotes.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top