Create text file and fill it using bash

前端 未结 5 690
一整个雨季
一整个雨季 2020-12-12 19:45

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?

5条回答
  •  不思量自难忘°
    2020-12-12 20:03

    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
    

    Edit about using:

    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
    

    Put the file in a directory in your path, then use it with:

    create_file 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.

提交回复
热议问题