Подтвердить что ты не робот

запись файла в скрипт bash

Я новичок в bash, но я пытаюсь написать скрипт bash, который делает следующее:

write_to_file()
{
 #check if file exists
 # if not create the file
 # else open the file to edit
 # go in a while loop
 # ask input from user 
 # write to the end of the file
 # until user types  ":q"

 }

Если кто-нибудь может указать на литературу, я был бы очень благодарен Спасибо

4b9b3361

Ответ 1

Обновление. Поскольку это вопрос bash, вы должны попробовать это первым. ;)

cat <<':q' >> test.file

Чтобы понять, что происходит, читайте о перенаправлении bash IO, синтаксисе heredoc и команде cat


Как вы видите выше, есть много способов сделать это. Чтобы объяснить несколько команд bash, я подготовил эту функцию так же, как вы ее запросили:

#!/bin/bash

write_to_file()
{

     # initialize a local var
     local file="test.file"

     # check if file exists. this is not required as echo >> would 
     # would create it any way. but for this example I've added it for you
     # -f checks if a file exists. The ! operator negates the result
     if [ ! -f "$file" ] ; then
         # if not create the file
         touch "$file"
     fi

     # "open the file to edit" ... not required. echo will do

     # go in a while loop
     while true ; do
        # ask input from user. read will store the 
        # line buffered user input in the var $user_input
        # line buffered means that read returns if the user
        # presses return
        read user_input

        # until user types  ":q" ... using the == operator
        if [ "$user_input" == ":q" ] ; then
            return # return from function
        fi

        # write to the end of the file. if the file 
        # not already exists it will be created
        echo "$user_input" >> "$file"
     done
 }

# execute it
write_to_file

Ответ 2

Пример с основными проверками аргументов:

write_to_file()
{
    while [ "$line" != ":q" ]; do
        read line
        if [ "$line" != ":q" ]; then
            printf "%s\n" "$line" >> "$1"
        fi  
    done
}

if [ "$#" -eq 1 ]; then
    write_to_file "$1"
else
    echo "Usage: $0 FILENAME"
    exit 2
fi

Или, используя, вероятно, менее известный до построения, функцию можно записать немного более кратким:

# append to file ($1) user supplied lines until ':q' is entered
write_to_file()
{
    until read line && [ "$line" = ":q" ]; do
        printf "%s\n" "$line" >> "$1"
    done
}

Ответ 3

Этот быстрый пример должен помочь вам начать:

while true
do
    read INPUT
    if [[ "${INPUT}" == :q ]]
    then
        return
    fi
    echo "${INPUT}" >> file
done

Ответ 4

Здесь есть несколько решений, которые слишком усложняются. Просто делать:

write_to_file() { sed '/^:q$/q' | sed '$d' >>"$1"; }

где первым аргументом является имя файла. То есть, вызывают это как:

write_to_file test.file