linux - sed - 没有那个文件或目录

标签 linux bash centos

所以,我知道这个主题已经通过多种方式进行了讨论,但回复对我不起作用。

我正在使用 sed 从脚本中删除一行,但每次执行 bash 脚本时,我都会收到一条错误消息“没有这样的文件或目录”。我可以从远程主机终端运行命令。请参阅下面的 sed 命令。

#!/bin/bash

declare server_list="/location/of/iplist.txt"
declare file="/location/of/file/to/modify"
declare regex='"/\export JAVA_HOME=\/jvm\/home\/directory\/java/d"'
declare file_content="$(sudo grep -Fxq export 
JAVA_HOME=/java/home/directory/java "${file}" )

declare script="sudo sed -i -e ${regex} ${file}"

date
cat ${server_list} |  while read server
do
# connect to each server and execute the "sed -i" command
ssh -I /location/of/pub/key ${server} -o StrictHostKeyChecking=no

# read file content into condition statement
${file_content}
if [ $? -eq 0 ];
then
    # confirm string exist and remove the line
    echo "JAVA_HOME located on ${server}"
    "${script}"
else
    echo "No JAVA_HOME located on ${server}"
fi
done

最佳答案

不要将完整的命令放在变量中。 "${script}" 是自找麻烦。

一个说明性的例子:

me ~ > echo -e 'foo bar\nbaz qux' > /tmp/foobar

me ~ > cat /tmp/foobar
foo bar
baz qux

me ~ > sed -e '/foo bar/d' /tmp/foobar
baz qux

me ~ > cmd="sed -e '/foo bar/d' /tmp/foobar"

me ~ > $cmd
sed: -e expression #1, char 1: unknown command: `''

me ~ > ${cmd}
sed: -e expression #1, char 1: unknown command: `''

me ~ > "$cmd"
bash: sed -e '/foo bar/d' /tmp/foobar: No such file or directory

me ~ > "${cmd}"
bash: sed -e '/foo bar/d' /tmp/foobar: No such file or directory

这是怎么回事?如果您使用未加引号的 $cmdsed 有以下 4 个参数:

  • -e
  • '/foo
  • bar/d'
  • /tmp/foobar

(是的,这就是 bash 中“单词”的工作方式)。显然 sed 不能解释这个乱码。

如果您尝试运行 "$cmd""${cmd}",整个字符串将被解释为命令 name,空格引号和所有。 shell 提示它找不到名为 sed -e '/foo bar/d'/tmp/foobar 的可执行文件,这是绝对正确的。也不好。

解决方案?

一个快速而肮脏的 hack 是

me ~ > eval ${cmd}
baz qux

按预期工作!然而,eval is dangerous除非您是经过认证的 shell 大师,否则不应使用。 (我相信你仍然不是)。更好的选择是定义一个函数。

cmd() {
    sed -e '/foo bar/d' /tmp/foobar
}

...

cmd

关于linux - sed - 没有那个文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395460/

相关文章:

ruby - 是否有 .bash_profile/.bash_rc/.profile 的 IRB 等价物?

proxy - Squid 代理缓存摘要

php - 编译安装php 5.3.9时zip.so在哪里

linux - 使用 shell 脚本从另一个文件检查用户名和密码

linux - 脚本导致 CPU 使用率高

c - 同级 .so 文件中符号的可见性

linux - 使用 bash 创建一个具有 2 个独立 View 部分的窗口

docker - Iscsid 未在 MacOS 主机上的 centos6 docker 上启动

linux - 行缓冲猫

linux - 寻找一种必须将 cron 输出到标准输出和日志文件的方法