创建文本文件并使用bash填充它 [英] Create text file and fill it using bash

查看:46
本文介绍了创建文本文件并使用bash填充它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个文本文件(除非它已经存在),并使用bash将新行写到该文件中.

I need to create a text file (unless it already exists) and write a new line to the file all using bash.

我敢肯定这很简单,但是有人可以向我解释吗?

I'm sure it's simple, but could anyone explain this to me?

推荐答案

如果您希望将其作为脚本,则以下Bash脚本应该执行您想要的操作(并告诉您文件已存在的时间):

If you're wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):

#!/bin/bash
if [ -e $1 ]; then
  echo "File $1 already exists!"
else
  echo >> $1
fi

如果您不希望已经存在"消息,则可以使用:

If you don't want the "already exists" message, you can use:

#!/bin/bash
if [ ! -e $1 ]; then
  echo >> $1
fi

编辑有关使用的信息:

使用您喜欢的名称保存任何版本,例如说"create_file"(引用我的名字,您不希望它们出现在文件名中).然后,要使该文件可执行,请在命令提示符下执行以下操作:

Save whichever version with a name you like, let's say "create_file" (quotes mine, you don't want them in the file name). Then, to make the file executatble, at a command prompt do:

chmod u+x create_file

将文件放在路径中的目录中,然后将其用于:

create_file NAME_OF_NEW_FILE

$ 1是一个特殊的shell变量,它在命令行中使用程序名称之后的第一个参数;即$ 1将在上述用法示例中提取NAME_OF_NEW_FILE.

The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.

这篇关于创建文本文件并使用bash填充它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆