在shell脚本中使用sed替代项不起作用 [英] use of sed substitute in shell script doesn't work
问题描述
我制作了一个安装脚本,该脚本基本上在外壳脚本中使用 sed
在 RewriteEngine On 行之后插入了 RewriteRule >
I have made an install script which basically inserts some RewriteRule right after RewriteEngine On line by using sed
inside a shell script
#!/bin/bash
REWRITE_RULE="RewriteRule \^catalog\/category\/view\/id\/([0-9]+)$ http:\/\/localhost\/app\/#?c=$1 [NE,L,R=301]"
FILE_PATH=".htaccess"
sed -i "s/RewriteEngine on/RewriteEngine on\n\n$REWRITE_RULE/g" $FILE_PATH
它什么都不做,但会给出类似的错误
it does nothing but gives some error like
:没有这样的文件或目录
: No such file or directory
我在shell中尝试了相同的命令,但没有任何问题,并更新了我的 .htaccess 文件
I tried same commands in shell and it worked without any issues and updated my .htaccess file
我是shell脚本的新手,所以不知道通过shell和脚本使用相同命令的区别.请指导
I am new to shell scripting so don't know the difference of using same command through shell and through script.. please guide
推荐答案
您会发现您的脚本包含回车符,这是因为它是用DOS行尾字符保存的.使用 tr -d'\ r'< brokenscript> fixedscript
修复脚本.
You'll find that your script contains carriage returns due to being saved with DOS end-of-line characters. Use tr -d '\r' <brokenscript >fixedscript
to fix your script.
以下是该会话的副本,该会话已复制并解决了该问题:
Here's a copy of a session with the problem reproduced and fixed:
$ cat file
var=foo
$ cat myscript
sed -i s/foo/bar/ file
$ bash myscript
: No such file or directory
$ shellcheck myscript
In myscript line 1:
sed -i s/foo/bar/ file
^-- SC1017: Literal carriage return. Run script through tr -d '\r' .
$ tr -d '\r' < myscript > fixedscript
$ bash fixedscript
$ cat file
var=bar
$
这篇关于在shell脚本中使用sed替代项不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!