简体   繁体   English

如何通过$ @将包含空格的sed命令传递给Bash函数

[英]How to pass sed command with spaces in expression to Bash function through $@

I would need to replace a string having spaces with another string in a file in a bash script where all calls should be done through a function that writes the command to a log file and then runs the command. 我需要在bash脚本中的文件中替换具有空格的字符串,其中所有调用都应该通过将命令写入日志文件然后运行命令的函数来完成。 The logrun function uses special character $@ for reading in the command. logrun函数使用特殊字符$@来读取命令。 I'm trying to use sed for replacing but I can't find a way to escape spaces when the sed command having spaces in expression parameter goes through $@ . 我正在尝试使用sed进行替换,但是当表达式参数中包含空格的sed命令通过$@时,我找不到逃避空格的方法。

I have simplified the problem to test scripts where I use sed for replacing ac with abc . 我已经简化了测试脚本的问题,我使用sed替换acabc

test1.sh works great: test1.sh效果很好:

#!/bin/bash

TESTFILE=/tmp/test.txt
echo "a c" > $TESTFILE
sed -i -e 's/a c/a b c/' $TESTFILE

test2.sh fails: test2.sh失败:

#!/bin/bash

function logrun() {
    CMD=$@
    $CMD
}

TESTFILE=/tmp/test.txt
echo "a c" > $TESTFILE
logrun sed -i -e 's/a c/a b c/' $TESTFILE

Result: 结果:

sed: -e expression #1, char 3: unterminated `s' command

The reason for error is the space(s) in the -e expression. 错误的原因是-e表达式中的空格。 I haven't found a way to call sed through that function. 我还没有找到通过该函数调用sed的方法。 I have tried to use double quotes instead of single quotes and to escape spaces with a backslash etc. I am really curious to find out what's the correct way to do it. 我试图使用双引号而不是单引号并使用反斜杠等来转义空格。我真的很想知道正确的方法是什么。

logrun() {
    CMD=("$@")
    "${CMD[@]}"
}

Writing $@ without quotes combines all of the arguments into one space-separated string. 编写没有引号的$@将所有参数组合成一个以空格分隔的字符串。 "$@" with quotes keeps each argument separate and preserves whitespace. 带引号的"$@"将每个参数分开并保留空格。

Writing just CMD="$@" would create a simple string variable. 只写CMD="$@"会创建一个简单的字符串变量。 CMD=("$@") creates an array. CMD=("$@")创建一个数组。

Then, to expand the array, use the same syntax as you did with PARAMS : "${CMD[@]}" . 然后,要扩展数组,请使用与PARAMS相同的语法: "${CMD[@]}" The quotes and the two sets of braces are all necessary. 引号和两组括号都是必需的。 Don't leave any of them out. 不要把它们中的任何一个留下来。

By the way, if you don't need the CMD variable, it could be a lot less verbose: 顺便说一下,如果你不需要CMD变量,它可能会更简洁:

logrun() {
    "$@"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM