gpt4 book ai didi

bash - 在 bash 脚本中写入文件

转载 作者:行者123 更新时间:2023-11-29 08:48:48 24 4
gpt4 key购买 nike

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

}

谁能指出文献,不胜感激谢谢

最佳答案

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

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

要了解发生了什么,请阅读 bash 的 IO redirection , heredoc 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

关于bash - 在 bash 脚本中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637284/

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