gpt4 book ai didi

linux - 如何从 bash 函数打开编辑器?

转载 作者:太空狗 更新时间:2023-10-29 12:22:04 25 4
gpt4 key购买 nike

我有一个简单的功能来打开编辑器:

open_an_editor(){    nano "$1"}

如果像 open_an_editor file.ext 这样调用,它就可以工作。但是,如果我需要从函数中获取一些输出 — smth=$(open_an_editor file.ext) — 我看不到编辑器,脚本就会卡住。我在这里缺少什么?

更新:我正在尝试编写一个函数,它会要求用户在编辑器中写入一个值,如果它没有在脚本参数中给出的话。

#!/bin/bashopen_an_editor(){    if [ "$1" ]    then        echo "$1"        return 0    fi    tmpf=$(mktemp -t pref)    echo "default value, please edit" > "$tmpf"    # and here the editor should show up,    # allowing user to edit the value and save it    # this will stuck without showing the editor:    #nano "$tmpf"    # but this, with the help of Kimvais, works perfectly:    nano "$tmpf" 3>&1 1>&2 2>&3    cat "$tmpf"    rm "$tmpf"}something=$(open_an_editor "$1")# and then I can do something useful with that value,# for example count chars in itecho -n "$something" | wc -c

因此,如果使用参数 ./script.sh "A value" 调用脚本,该函数将只使用该参数并立即回显 7 个字节。但是如果不带参数调用 ./script.sh — nano 应该弹出。

最佳答案

如果您需要的输入是编辑后的文件,那么您显然需要在执行 open_an_editor filename 之后 cat filename

如果您确实需要编辑器的输出,那么您需要交换 stderr 和 stdin 即:nano "$1"3>&1 1>&2 2>&3

如果您需要“友好”的用户输入,请参阅 this question关于如何使用whiptail

关于linux - 如何从 bash 函数打开编辑器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2361181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com