用bash脚本编写文件

时间:2013-01-31 23:47:27

标签: bash unix

我是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"

 }

如果有人能指出文献,我会非常感激 感谢

4 个答案:

答案 0 :(得分:22)

更新:因为这是一个重击问题,你应该先试试。 ;)

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

要了解正在发生的事情,请阅读bash的IO redirectionheredoc syntaxcat命令


如上所述,有很多方法可以做到这一点。为了解释一些更多的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

答案 1 :(得分:6)

基本参数检查的示例:

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

或者使用可能鲜为人知的until结构,该函数可以写得更简洁:

# 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
}

答案 2 :(得分:2)

这个快速示例可以帮助您入门:

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

答案 3 :(得分:2)

这里有几个解决方案太难用了方式。只是做:

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

其中第一个参数是文件的名称。也就是说,将其调用为:

write_to_file test.file