Linux script to create files

Create text file and fill it using 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?

9 Answers 9

Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this

echo "insert text here" > myfile.txt 

That will put the text ‘insert text here’ into a file myfile.txt. To verify that this worked use the command ‘cat’.

If you want to append to a file use this

echo "append this text" >> myfile.txt 

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 

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:

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.

@Switz: See edit explaining $1. If you replace $1 in the script with «text.txt», it will always use «text.txt» as the filename.

Assuming you mean UNIX shell commands, just run

echo prints a newline, and the >> tells the shell to append that newline to the file, creating if it doesn’t already exist.

In order to properly answer the question, though, I’d need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use

EDIT: and in response to Justin’s comment, if you want to add the newline only if the file didn’t already exist, you can do

test -e file.txt || echo > file.txt 

At least that works in Bash, I’m not sure if it also does in other shells.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Create multiple directories and files, and populate files with a shell script. (Linux, MacOS, and Windows)

Читайте также:  Vmware converter and linux

samwhindleton/make-files-script

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Create Files and Folders With a Shell Script

Create multiple directories and files, and populate files with a shell script. (Linux, MacOS, and Windows)

In this guide we’ll be creating multiple directories and files, and add text to files with a shell script. You’ll create and run the script. Follow the Linux and MacOS Guide if you have a Linux flavored or MacOS OS, or follow the Windows Guide if you have a Windows OS.

We’ll be using a for loop to create:

Type the command and press enter

terminal

A new file make.sh will be created and opened in the nano editor.

nano

NOTE: If you don’t have nano installed, visit Nano to download and install it.

brew update brew install nano
# variable name is directoryName # directoryName value is folder-name- directoryName=folder-name-

variable-1

# variable name is htmlFile # htmlFile value is index.html htmlFile=index.html # variable name is cssFile # cssFile value is style.css cssFile=style.css

variable-2

# variable name is htmlTemplate # htmlTemplate has a multi-line value that includes spaces # default html template htmlTemplate="  "

variable-3

  1. Create an empty for loop that iterates number thru a number range of 1 to 5 and displays done. when the for loop is complete
# number range for loop # iterates thru a range of numbers for number in ; do # end of for loop done # display done. when for loop is complete echo done.

for-loop-1

mkdir $directoryName$number

for-loop-2

  1. Create files inside the directory directoryName + number with the name of the variable htmlFile and cssFile
touch $directoryName$number/$htmlFile $directoryName$number/$cssFile

for-loop-3

  1. Add text from the variable htmlTemplate to the file html.index that is located in the directory directoryName + number
echo "$htmlTemplate" >> $directoryName$number/$htmlFile

for-loop-4

save

Then exit nano by pressing ctrl + X .

exit

  1. In order to run make.sh we need to change its file permission to read, write, execute. Read more about Permissions here.

chmod700

run

chmod644

View Created Files and Folders

finder

finder

Type the command and press enter.

A new file make.bat will be created and opened in the nano editor.

NOTE: If you don’t have nano installed, visit Nano to download and install it.

set directoryName=folder-name-
set htmlFile=index.html set cssFile=style.css
set htmlTemplate=^!DOCTYPE html^>^ ^html lang="en"^>^ ^head^>^ ^meta charset="utf-8"^>^ ^title^>^/title^>^ ^/head^>^ ^body^>^ ^/body^>^ ^/html^>
  1. Create an empty for loop that iterates %%A thru a number range of 1 to 5 (1, 1, 5) and displays done. when the for loop is complete.
for /l %%A in (1, 1, 5) do ( ) echo done
  1. Create files inside the directory directoryName + %%A with the name of the variable htmlFile and cssFile .
type nul > %directoryName%%%A\%htmlFile% && type nul > %directoryName%%%A\%cssFile%
  1. Add text from the variable htmlTemplate to the file html.index that is located in the directory directoryName + %%A .
echo !htmlTemplate! > %directoryName%%%A\%htmlFile%

Then exit nano by pressing ctrl + X .

View Created Files and Folders

There are pre-made scripts in the scripts directory. They all create five named or numbered directories with a html.index and style.css file. The html.index file will have a default html template populated.

  • The scripts/linux-mac directory has two scripts.
    1. Creates named directories

Resulting folder structure:

foo-bar/ ├── folder-name-sophia/ │ ├── index.html │ └── style.css ├── folder-name-jackson/ │ ├── index.html │ └── style.css ├── folder-name-emma/ │ ├── index.html │ └── style.css ├── folder-name-aiden/ │ ├── index.html │ └── style.css └── folder-name-olivia/ ├── index.html └── style.css make-name.sh

Resulting folder structure:

foo-bar/ ├── folder-name-1/ │ ├── index.html │ └── style.css ├── folder-name-2/ │ ├── index.html │ └── style.css ├── folder-name-3/ │ ├── index.html │ └── style.css ├── folder-name-4/ │ ├── index.html │ └── style.css └── folder-name-5/ ├── index.html └── style.css make-num.sh

Resulting folder structure:

foo-bar\ ├── folder-name-sophia\ │ ├── index.html │ └── style.css ├── folder-name-jackson\ │ ├── index.html │ └── style.css ├── folder-name-emma\ │ ├── index.html │ └── style.css ├── folder-name-aiden\ │ ├── index.html │ └── style.css └── folder-name-olivia\ ├── index.html └── style.css make-name.bat

Resulting folder structure:

foo-bar\ ├── folder-name-1\ │ ├── index.html │ └── style.css ├── folder-name-2\ │ ├── index.html │ └── style.css ├── folder-name-3\ │ ├── index.html │ └── style.css ├── folder-name-4\ │ ├── index.html │ └── style.css └── folder-name-5\ ├── index.html └── style.css make-num.bat

About

Create multiple directories and files, and populate files with a shell script. (Linux, MacOS, and Windows)

Источник

Creating files with some content with shell script

I need to configure a server with a few files and I want to do it programmatically. I need to create files say /home/a.config, /var/spool/b.config, /etc/c.config Files above have some contents (multi lines). I want to create ONE shell script which can create all three file with multiple lines (around 10). I would like to know the how can I use CAT command to do that. (inside shell script). I am looking something like this

echo " going to create /home/a.config" cat "HOW CAN I HAVE MULTIPLE LINES HERE?? " > /home/a.config 

5 Answers 5

cat filename first line second line third line EOF 

You can place several of these in the same script.

@Nagev: If you don’t want any parameter expansion, command substitution, and arithmetic expansion in the here document you can quote the beginning delimiter ‘EOF’ instead of having to escape each individual dollar sign.

@JúlioFalbo: If you don’t quote the here doc delimiter (e.g. EOF ) then parameters (variables) in the text will be expanded.

file="/tmp/test.txt" echo "Adding first line" > $file echo "Adding first line replaced" > $file echo "Appending second line " >> $file echo "Appending third line" >> $file cat $file 

> to add/replace the content ( here actual content got replaced by the 2nd line)
>> to append

Result
Adding first line replaced
Appending second line
Appending third line

#!/bin/bash var="your text" echo "simply put, just so: $var" > a.config 

For further info, see Input/Output part of abs.
Hope, this helps.

If you’ve got variables like $1 or $HOMEDIR in your text then these normally get evaluated and substituted with actual values. If you want to prevent these from getting substituted then you need to quote the opening limit string (EOF in example below) with single quote ‘EOF’ , double quote «EOF» or precede it with backslash \EOF

Closing limit string stays as is. EOF

This is especially useful if you are writing shell scripts to a file.

cat /etc/rc.d/init.d/startup case $1 in start) start ;; stop) stop ;; restart) stop start ;; status) pid=$(tomcat_pid) if [ -n "$pid" ] then echo "Tomcat is running with pid: $pid" else echo "Tomcat is not running" fi ;; esac EOF 

Refer Example 19.7 Parameter Substitution Turned off in Here Documents

Источник

How to create a file in Linux from terminal window? [closed]

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.
 eg: grep --help > randomtext.txt echo "This is some text" > randomtext.txt 

UNIX is not a command line environment, but a family of (very different) OSes. That said: Yes, this should work on most Unices

touch will work in UNIX, because it’s a standard tool. The somecommand example will work because it uses standard syntax. The nano sample may not work because an editor named nano may not be installed (nano is not standardized). The standard editor is ed and could be used in place of nano , or you could use $EDITOR to use your user- or system-configured default text editor, if there is one.

Additionally, you could simply say >/path/to/file to create an empty file, even if you don’t have touch .

Create the file using cat

Now, just type whatever you want in the file:

When I tried cat /etc/systemd/system/sample.service , it said «no such file or directory» rather than creating a new sample.service file.

@TylerH cat /etc/systemd/system/sample.service prints the file to the console cat > /etc/systemd/system/sample.service redirects standard input to the file (which is why you need to close standard input by pressing control-d.

There are several possible solutions:

Create an empty file

touch file >file echo -n > file printf '' > file 

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file printf '\n' > file 

This is a valid «text file» because it ends in a newline.

Write text into a file

"$EDITOR" file echo 'text' > file cat > file file 

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Источник

Оцените статью
Adblock
detector