linux - Bash:带有 sed 问题的 bash 中的自定义函数

标签 linux bash function shell sed

阅读这篇文章后,我尝试在 .bashrc 文件中添加自定义 bash 函数:https://unix.stackexchange.com/questions/38072/how-can-i-save-the-last-command-to-a-file

我基本上把

function getlast {
    fc -ln "$1" "$2" | sed '1s/^[[:space:]]*//'
}

在 .bashrc 中。

请注意,我已经从

更改了命令行
fc -ln "$1" "$1"

fc -ln "$1" "$2"

所以我可以更灵活地使用 fc 命令。

现在就

getlast

工作正常,因为它给出了我刚刚输入的最后一个命令。

但是,当我尝试将它与两个命令行参数一起使用时:

getlast -1 -3

我收到的错误消息基本上是 sed 帮助消息:

sed: invalid option -- '1'
Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...

-n, --quiet, --silent
             suppress automatic printing of pattern space
-e script, --expression=script
             add the script to the commands to be executed
-f script-file, --file=script-file
             add the contents of script-file to the commands to be executed
--follow-symlinks
             follow symlinks when processing in place
 -i[SUFFIX], --in-place[=SUFFIX]
             edit files in place (makes backup if extension supplied)
  ......

当我像这样使用 fc -ln 时

fc -ln -1 -3

它运行良好...而且它在命令行上也运行良好以在 fc 之后运行 sed。所以我知道这可能与 bash 有关...

我还尝试通过删除 ' ' 内的 1 和其他东西来扭曲 sed,但它没有用。我不明白为什么它不起作用...有人可以帮助我理解这里的问题吗?

谢谢。

[编辑]

我试图删除 sed 部分,所以在函数中只有:

function getlast {
    fc -ln "$1" "$2"
}

现在 getlast 仍然有效并且 getlast -1 -3 仍然给了我相同的错误消息,即使没有涉及 sed ...所以问题可能是还有什么?真的很迷茫……

[编辑2]

现在可以了。我不确定我明白到底发生了什么。

基本上,在阅读了 NeronLeVelu 的回答并尝试了很多东西之后,我意识到可能是特定的 bash session 有这个问题。所以我在 tmux 中打开了一个新窗口并尝试了 getlast -1 -2 现在它可以工作了......不再有 sed 错误......

不确定我正在处理的 session 中发生了什么……但现在可以了。

最佳答案

尝试在 sed 之后的 ' 之前添加 --posix 和/或 -e

function getlast() {
    fc -ln "$1" "$2" | sed --posix -e '1s/^[[:space:]]*//'
}

在 AIX 下(因此不允许使用 GNU sed 和 --posix)

bash-3.2$      echo "with space before\n"
with space before

bash-3.2$ getlast -1 -2

getlast -1 -2
+ getlast -1 -2
+ set -vx
+ fc -ln -1 -2
+ sed -e '1s/^[[:space:]]*//'
echo "with space before"
         getlast -1 -2

关于linux - Bash:带有 sed 问题的 bash 中的自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22034067/

相关文章:

linux - 需要帮助解决 Ubuntu Linux 上的 FTP 问题

c - OpenWrt LibUbi 实现

linux - 如何grep数字范围

bash - 将第一个字符与特殊字符分隔符一起转换为大写

python - 我的 mac 终端无法运行 python 函数

linux - filp_open 给出没有操作指针的文件指针?

使用标准 I/O 和系统调用制作文件副本的 C 程序

linux - 从许多 csv 文件中删除重复项

c - 从函数传递字符串

function - 使用 cv::equalizeHist() 的 OpenCV 直方图均衡过程:需要帮助理解最后一步