根据变量运行sed命令

时间:2018-07-20 12:13:21

标签: bash if-statement sed switch-statement

我正在尝试根据用户输入运行变量sed命令:

#!/bin/bash

ACTION=$1

if [ "wp" == "$ACTION"  ]
then
   MODIFIEDCONF='sed -i -e "/#Begin wp redirect/,/#End wp redirect/d" /root/test-conf'
else
   MODIFIEDCONF='sed -i -e "/#Begin ghost redirect/,/#End ghost redirect/d" /root/test-conf'
fi

RESULT=$($MODIFIEDCONF)

但是我得到了错误:

sed: -e expression #1, char 1: unknown command: `"'

如何解决该错误?还是有更好的方法呢?

4 个答案:

答案 0 :(得分:0)

尝试避免进行变量扩展,即运行$var。如果只在脚本中使用变量,请使用小写字母,并且只允许UPPERCASE_VARIABLES对导出的变量进行蜂鸣式操作是一种习惯。 为什么不这样:

#!/bin/bash

# get action
action=$1

# check action value
case "$action" 
wp) ;;
*) action=ghost; ;;
# or maybe: *) echo "ERROR: action has bad value! Exiting!" >&2; exit 1; ;;
esac

# run sed
result=$(sed -i -e "s/#Begin $action redirect/,/#End $action redirect/" /root/test-conf)

如果必须result=$($modifiedconf)使用bash数组:

if [ "wp" = "$action" ]; then
   modifiedconf=(sed -i -e "/#Begin wp redirect/,/#End wp redirect/d" /root/test-conf)
else
   modifiedconf=(sed -i -e "/#Begin ghost redirect/,/#End ghost redirect/d" /root/test-conf)
fi
result=$("${modifiedconf[@]}")

答案 1 :(得分:0)

使用函数存储代码,而不是字符串。

#!/bin/bash

ACTION=$1

if [ "wp" == "$ACTION"  ]
then 
   modify_conf() { sed -i -e "/#Begin wp redirect/,/#End wp redirect/d" /root/test-conf; }
else
   modify_conf() { sed -i -e "/#Begin ghost redirect/,/#End ghost redirect/d" /root/test-conf; }
fi

modify_conf

({modify_conf不会输出任何有用的信息,因此无需捕获其输出。)

或将ACTION作为参数传递:

modify_conf () {
  if [ "$1" = wp ]; then
    sed -i -e "/#Begin wp redirect/,/#End wp redirect/d" /root/test-conf
  else
    sed -i -e "/#Begin ghost redirect/,/#End ghost redirect/d" /root/test-conf
  fi
}

modify_conf "$ACTION"

答案 2 :(得分:0)

保持简单。在变量中设置sed命令模式,然后执行。

case "$ACTION" in
wp) cmd="/#Begin wp redirect/,/#End wp redirect/d"       ;;
 *) cmd="/#Begin ghost redirect/,/#End ghost redirect/d" ;;
esac

sed -i "$cmd" /root/test-conf

或者为了提高可读性,只需设置密钥并嵌入。

case "$ACTION" in
wp) key=wp    ;;
 *) key=ghost ;;
esac

sed -i "/#Begin $key redirect/,/#End $key redirect/d" /root/test-conf

抽象就是力量,但不必要的抽象就是迷惑。

答案 3 :(得分:-1)

要删除您报告的错误,您应该更改以下行:

 RESULT=$($MODIFIEDCONF)

收件人:

 eval "$MODIFIEDCONF"

有关此内容和参考的更多详细信息,请参见:

一个警告。命令eval确实有的声誉:例如参见Why should eval be avoided in Bash, and what should I use instead?。但是在这种情况下,它是完全安全eval "$MODIFIEDCONF"(此处为可选)中的多余引号有助于防止意外的错误。


次要点:您编写的sed命令将不返回任何文本(可能返回stderr除外)。如果您确实需要变量RESULT的值,请添加以下行:

  RESULT=$?

$RESULT将始终为0,除非文件/root/test-conf不存在(或者您的脚本碰巧具有无效的sed命令,情况并非如此)这里)。