将编辑框中的文件内容保存在 BASH

Save file content from editbox in BASH

我想学习 shell-脚本。我想创建一个简单的工具来显示带有编辑选项的文件内容,但我无法从 dialog --editbox 中获取值。任何人都可以向我解释它是如何工作的?

我的代码:

#!/bin/bash
BACKTITLE="Some backtitle"
FILENAME="filename.txt"

touch $FILENAME

INPUT=/tmp/menu.sh.$$

ret=0

while [ $ret -eq 0 ]
do
    dialog --title "Menu" \
        --backtitle "$BACKTITLE"  \
        --menu "Wybierz" 10 60 3 \
        1 "Pokaz menu" \
        2 "Edytuj" \
        2>"${INPUT}"

    ret=$?
    option=$(<"${INPUT}")

    if [ $ret -eq 0 ]
    then
        if [ $option -eq 1 ]
        then
            dialog --title "File content" \
                --backtitle "$BACKTITLE" \
                --textbox $FILENAME 10 60
        elif [ $option -eq 2 ]
        then
            dialog --title "Edit file content" \
                --backtitle "$BACKTITLE" \
                --editbox $FILENAME 10 60

            editboxret=$?
            echo $editboxret
            ret=0
        fi
    fi
done

对话框将 'edited' 内容写入 STDERR,您需要确保它再次出现在原始文件中。

# Write the output of dialog to a temp-file
dialog --editbox $FILENAME 10 60 2> "${INPUT}"

# ADVISED: Show the user the temporary file-content
# and ask for confirmation before doing the next step:

# Overwrite the input-file
cp ${INPUT} $FILENAME

根据联机帮助页 (man dialog),输出被写入 stderr。 使用中的建议,您可以使用

{ newcontents=$(dialog --title "Edit file content" -- backtitle "$BACKTITLE" --editbox $FILENAME 10 60 2>&1 1>&$out); } {out}>&1