Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a file in a specific directory using Bash?

Normally to create a file in a directory I would use:

echo > /home/user/fileName

but, in this case, my directory path I want to create the file in is stored in a variable in my script so I can't write out the path like that. How do I create a new file inside of it?

like image 437
Janikole Avatar asked Dec 06 '11 04:12

Janikole


People also ask

How do I create a file in a specific directory in Linux?

You can either click the Terminal icon in the Apps menu, or press Ctrl + Alt + T at the same time to open the Terminal. Navigate to the directory you want to create a file in. To do so, type cd followed by the path to the directory you want to create a file in and press Enter..

How do you create a file in bash?

To create a new file, run the "cat" command and then use the redirection operator ">" followed by the name of the file. Now you will be prompted to insert data into this newly created file. Type a line and then press "Ctrl+D" to save the file.

How do I create and write to a file in bash?

In bash scripting, there are multiple ways to write a file, but the simplest one is using redirection operators “>”, “>>”. To write multiple lines, “heredoc” can be used, and if you want to write the same data to multiple lines, then the “tee” command is quite handy.

How do I create a path in bash?

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called ~/. bash_profile, ~/. bashrc, or ~/.


2 Answers

If you have a variable myPath, you can use:

echo >${myPath}/fileName

as per the following transcript:

pax:~$ export myPath=/tmp

pax:~$ ls -al /tmp/x*
ls: cannot access /tmp/x*: No such file or directory

pax:~$ echo >${myPath}/xyzzy

pax:~$ ls -al /tmp/x*
-rw-r--r-- 1 pax pax 1 2011-12-06 12:30 /tmp/xyzzy
like image 113
paxdiablo Avatar answered Oct 20 '22 01:10

paxdiablo


Just use:

echo > ${WHATEVER}/fileName
like image 36
David Schwartz Avatar answered Oct 20 '22 00:10

David Schwartz