How to Find Path and Upload Shel
Working With Files and Directories
Overview
Didactics: 30 min
Exercises: 20 minQuestions
How can I create, copy, and delete files and directories?
How can I edit files?
Objectives
Create a directory hierarchy that matches a given diagram.
Create files in that hierarchy using an editor or by copying and renaming existing files.
Delete, copy and move specified files and/or directories.
Creating directories
We now know how to explore files and directories, but how exercise nosotros create them in the showtime identify?
In this episode we volition learn about creating and moving files and directories, using the do-data/writing directory as an case.
Stride i: see where we are and what we already take
We should still exist in the trounce-lesson-data directory on the Desktop, which nosotros can checking using:
/Users/nelle/Desktop/shell-lesson-information Next nosotros'll move to the exercise-data/writing directory and come across what it contains:
$ cd exercise-information/writing/ haiku.txt LittleWomen.txt Create a directory
Allow's create a new directory called thesis using the command mkdir thesis (which has no output):
As you might guess from its proper name, mkdir ways 'brand directory'. Since thesis is a relative path (i.e., does not have a leading slash, like /what/ever/thesis), the new directory is created in the current working directory:
haiku.txt LittleWomen.txt thesis/ Since nosotros've just created the thesis directory, at that place'southward cipher in it however:
Note that mkdir is not limited to creating single directories i at a time. The -p option allows mkdir to create a directory with nested subdirectories in a single operation:
$ mkdir -p ../project/data ../projection/results The -R option to the ls command will list all nested subdirectories within a directory. Let's use ls -FR to recursively list the new directory hierarchy nosotros merely created in the project directory:
../project/: information/ results/ ../projection/data: ../projection/results: Two ways of doing the same thing
Using the shell to create a directory is no unlike than using a file explorer. If you open the current directory using your operating system'southward graphical file explorer, the
thesisdirectory will appear in that location as well. While the shell and the file explorer are two different means of interacting with the files, the files and directories themselves are the aforementioned.
Expert names for files and directories
Complicated names of files and directories can make your life painful when working on the command line. Here we provide a few useful tips for the names of your files and directories.
Don't use spaces.
Spaces can make a name more meaningful, just since spaces are used to separate arguments on the control line it is better to avoid them in names of files and directories. Y'all can utilize
-or_instead (eastward.thousand.n-pacific-gyre/rather thann pacific gyre/). To test this out, endeavour typingmkdir north pacific rolland see what directory (or directories!) are made when you check withls -F.Don't brainstorm the proper noun with
-(dash).Commands treat names starting with
-as options.Stick with messages, numbers,
.(period or 'full stop'),-(dash) and_(underscore).Many other characters have special meanings on the control line. Nosotros volition acquire nigh some of these during this lesson. There are special characters that tin can crusade your command to non work as expected and can even event in data loss.
If you demand to refer to names of files or directories that take spaces or other special characters, you should surround the proper name in quotes (
"").
Create a text file
Let's modify our working directory to thesis using cd, then run a text editor called Nano to create a file called draft.txt:
$ cd thesis $ nano draft.txt Which Editor?
When we say, '
nanois a text editor' we actually do mean 'text': it can simply work with evidently grapheme information, non tables, images, or any other human-friendly media. We use it in examples because it is one of the least complex text editors. However, because of this trait, it may not be powerful enough or flexible plenty for the work y'all need to do later on this workshop. On Unix systems (such as Linux and macOS), many programmers utilize Emacs or Vim (both of which require more time to learn), or a graphical editor such as Gedit. On Windows, you may wish to use Notepad++. Windows also has a congenital-in editor chosennotepadthat tin exist run from the command line in the same mode every bitnanofor the purposes of this lesson.No affair what editor you lot use, you will need to know where information technology searches for and saves files. If you get-go it from the beat out, information technology volition (probably) use your current working directory as its default location. If you utilize your reckoner'southward start carte du jour, it may want to save files in your desktop or documents directory instead. Y'all can change this past navigating to some other directory the beginning time you 'Save Every bit…'
Let's blazon in a few lines of text. In one case we're happy with our text, we can press Ctrl+O (press the Ctrl or Control key and, while holding it downwardly, press the O key) to write our information to disk (we'll be asked what file we desire to save this to: press Return to accept the suggested default of typhoon.txt).
Once our file is saved, we tin use Ctrl+X to quit the editor and return to the shell.
Control, Ctrl, or ^ Key
The Command key is also called the 'Ctrl' key. There are various ways in which using the Control central may be described. For case, y'all may see an education to press the Control key and, while holding it down, press the X key, described every bit any of:
Command-XControl+XCtrl-XCtrl+X^10C-10In nano, along the bottom of the screen you'll see
^1000 Get Aid ^O WriteOut. This means that yous can utilizeControl-Kto get aid andControl-Oto salve your file.
nano doesn't leave whatever output on the screen afterward information technology exits, but ls now shows that we accept created a file chosen draft.txt:
Creating Files a Different Manner
We have seen how to create text files using the
nanoeditor. Now, try the following command:
What did the
touchcommand do? When you look at your current directory using the GUI file explorer, does the file show up?Use
ls -lto inspect the files. How big ismy_file.txt?When might you want to create a file this manner?
Solution
The
impactcommand generates a new file calledmy_file.txtin your current directory. You can find this newly generated file by typinglsat the control line prompt.my_file.txttin can too exist viewed in your GUI file explorer.When you inspect the file with
ls -l, annotation that the size ofmy_file.txtis 0 bytes. In other words, information technology contains no information. If you openmy_file.txtusing your text editor it is blank.Some programs practise not generate output files themselves, but instead require that empty files have already been generated. When the program is run, it searches for an existing file to populate with its output. The bear on command allows you lot to efficiently generate a bare text file to be used by such programs.
What's In A Proper noun?
You may accept noticed that all of Nelle'due south files are named 'something dot something', and in this part of the lesson, we always used the extension
.txt. This is but a convention: we can phone call a filemythesisor almost anything else we want. Notwithstanding, near people use ii-part names most of the time to help them (and their programs) tell different kinds of files apart. The second part of such a name is called the filename extension and indicates what type of data the file holds:.txtsignals a plain text file,.cfgis a configuration file full of parameters for some program or other,.pngis a PNG epitome, and and so on.This is just a convention, albeit an of import i. Files contain bytes: it's up to us and our programs to interpret those bytes according to the rules for evidently text files, PDF documents, configuration files, images, and and so on.
Naming a PNG paradigm of a whale as
whale.mp3doesn't somehow magically turn it into a recording of whale song, though it might cause the operating organisation to effort to open it with a music histrion when someone double-clicks it.
Moving files and directories
Returning to the beat-lesson-data/writing directory,
$ cd ~/Desktop/shell-lesson-data/writing In our thesis directory we have a file draft.txt which isn't a particularly informative proper name, and then let's change the file'south proper name using mv, which is short for 'move':
$ mv thesis/typhoon.txt thesis/quotes.txt The first argument tells mv what we're 'moving', while the second is where it's to go. In this case, we're moving thesis/draft.txt to thesis/quotes.txt, which has the aforementioned effect every bit renaming the file. Sure plenty, ls shows us that thesis now contains one file called quotes.txt:
One must be careful when specifying the target file name, since mv volition silently overwrite any existing file with the same name, which could atomic number 82 to information loss. An boosted option, mv -i (or mv --interactive), can be used to make mv ask you for confirmation before overwriting.
Notation that mv too works on directories.
Let's movement quotes.txt into the current working directory. We utilise mv once again, just this time we'll use just the name of a directory as the second argument to tell mv that we want to proceed the filename but put the file somewhere new. (This is why the control is chosen 'move'.) In this case, the directory proper name we use is the special directory proper name . that we mentioned earlier.
The upshot is to move the file from the directory information technology was in to the current working directory. ls now shows usa that thesis is empty:
Alternatively, we can confirm the file quotes.txt is no longer present in the thesis directory by explicitly trying to listing it:
ls: cannot access 'thesis/quotes.txt': No such file or directory ls with a filename or directory as an argument only lists the requested file or directory. If the file given every bit the argument doesn't be, the shell returns an fault as we saw in a higher place. We can utilize this to see that quotes.txt is now present in our current directory:
Moving Files to a new binder
After running the post-obit commands, Jamie realizes that she put the files
sucrose.datandmaltose.datinto the incorrect folder. The files should accept been placed in therawbinder.$ ls -F analyzed/ raw/ $ ls -F analyzed fructose.dat glucose.dat maltose.dat sucrose.dat $ cd analyzedFill up in the blanks to motility these files to the
raw/binder (i.e. the 1 she forgot to put them in)$ mv sucrose.dat maltose.dat ____/____Solution
$ mv sucrose.dat maltose.dat ../rawCall back that
..refers to the parent directory (i.e. one above the current directory) and that.refers to the current directory.
Copying files and directories
The cp command works very much like mv, except information technology copies a file instead of moving it. We can check that it did the right affair using ls with 2 paths as arguments — like almost Unix commands, ls tin can exist given multiple paths at once:
$ cp quotes.txt thesis/quotations.txt $ ls quotes.txt thesis/quotations.txt quotes.txt thesis/quotations.txt We can also copy a directory and all its contents by using the recursive option -r, e.1000. to back upwardly a directory:
$ cp -r thesis thesis_backup Nosotros can bank check the result past listing the contents of both the thesis and thesis_backup directory:
$ ls thesis thesis_backup thesis: quotations.txt thesis_backup: quotations.txt Renaming Files
Suppose that you created a obviously-text file in your electric current directory to contain a list of the statistical tests y'all will demand to practise to clarify your data, and named it:
statstics.txtAfter creating and saving this file you realize you misspelled the filename! You want to correct the mistake, which of the post-obit commands could you utilize to practice then?
cp statstics.txt statistics.txtmv statstics.txt statistics.txtmv statstics.txt .cp statstics.txt .Solution
- No. While this would create a file with the correct name, the incorrectly named file even so exists in the directory and would demand to be deleted.
- Yes, this would work to rename the file.
- No, the period(.) indicates where to move the file, but does not provide a new file name; identical file names cannot be created.
- No, the period(.) indicates where to copy the file, but does non provide a new file name; identical file names cannot be created.
Moving and Copying
What is the output of the endmost
lscommand in the sequence shown below?$ mkdir recombined $ mv proteins.dat recombined/ $ cp recombined/proteins.dat ../proteins-saved.dat $ ls
proteins-saved.dat recombinedrecombinedproteins.dat recombinedproteins-saved.datSolution
We get-go in the
/Users/jamie/datadirectory, and create a new folder calledrecombined. The second line moves (mv) the fileproteins.datto the new folder (recombined). The third line makes a re-create of the file we just moved. The tricky part hither is where the file was copied to. Recall that..means 'go upwardly a level', so the copied file is at present in/Users/jamie. Discover that..is interpreted with respect to the current working directory, non with respect to the location of the file being copied. Then, the but thing that will show using ls (in/Users/jamie/data) is the recombined binder.
- No, see explanation to a higher place.
proteins-saved.datis located at/Users/jamie- Yes
- No, see explanation above.
proteins.datis located at/Users/jamie/data/recombined- No, see explanation above.
proteins-saved.datis located at/Users/jamie
Removing files and directories
Returning to the crush-lesson-data/writing directory, permit's tidy up this directory by removing the quotes.txt file we created. The Unix command we'll use for this is rm (short for 'remove'):
We can ostend the file has gone using ls:
ls: cannot access 'quotes.txt': No such file or directory Deleting Is Forever
The Unix shell doesn't have a trash bin that we can recover deleted files from (though most graphical interfaces to Unix exercise). Instead, when nosotros delete files, they are unlinked from the file arrangement so that their storage space on disk can be recycled. Tools for finding and recovering deleted files do be, simply there's no guarantee they'll work in any detail situation, since the reckoner may recycle the file's disk space right away.
Using
rmSafelyWhat happens when we execute
rm -i thesis_backup/quotations.txt? Why would we want this protection when usingrm?Solution
rm: remove regular file 'thesis_backup/quotations.txt'? yThe
-ioption volition prompt before (every) removal (employ Y to confirm deletion or N to continue the file). The Unix shell doesn't have a trash bin, so all the files removed will disappear forever. By using the-ioption, we have the chance to cheque that nosotros are deleting merely the files that we want to remove.
If we try to remove the thesis directory using rm thesis, we get an fault message:
rm: cannot remove `thesis': Is a directory This happens because rm past default just works on files, not directories.
rm tin can remove a directory and all its contents if nosotros use the recursive pick -r, and it volition do so without any confirmation prompts:
Given that there is no manner to retrieve files deleted using the vanquish, rm -r should be used with bang-up circumspection (you might consider adding the interactive option rm -r -i).
Operations with multiple files and directories
Often 1 needs to copy or move several files at once. This can be done by providing a list of private filenames, or specifying a naming pattern using wildcards.
Copy with Multiple Filenames
For this exercise, you tin can examination the commands in the
beat out-lesson-data/exercise-datadirectory.In the example below, what does
cpdo when given several filenames and a directory name?$ mkdir fill-in $ cp creatures/minotaur.dat creatures/unicorn.dat backup/In the instance below, what does
cppractise when given three or more than file names?basilisk.dat minotaur.dat unicorn.dat$ $ cp minotaur.dat unicorn.dat basilisk.datSolution
If given more than i file name followed by a directory name (i.e. the destination directory must be the last argument),
cpcopies the files to the named directory.If given iii file names,
cpthrows an error such every bit the one beneath, because information technology is expecting a directory name every bit the last argument.cp: target 'basilisk.dat' is not a directory
Using wildcards for accessing multiple files at once
Wildcards
*is a wildcard, which matches zero or more characters. Permit's consider thebeat out-lesson-data/exercise-data/proteinsdirectory:*.pdbmatchesethane.pdb,propane.pdb, and every file that ends with '.pdb'. On the other hand,p*.pdbonly matchespentane.pdbandpropane.pdb, because the 'p' at the forepart but matches filenames that begin with the letter 'p'.
?is also a wildcard, but it matches exactly one character. So?ethane.pdbwould lucifermethane.pdbwhereas*ethane.pdbmatches bothethane.pdb, andmethane.pdb.Wildcards can be used in combination with each other e.one thousand.
???i.pdbmatches three characters followed byane.pdb, givingcubane.pdb ethane.pdb octane.pdb.When the crush sees a wildcard, information technology expands the wildcard to create a list of matching filenames before running the command that was asked for. As an exception, if a wildcard expression does non match any file, Bash will pass the expression as an statement to the command every bit it is. For example, typing
ls *.pdfin theproteinsdirectory (which contains only files with names catastrophe with.pdb) results in an error message that there is no file calledwcandlssee the lists of file names matching these expressions, but non the wildcards themselves. It is the shell, not the other programs, that deals with expanding wildcards.
List filenames matching a pattern
When run in the
proteinsdirectory, whichlscommand(due south) will produce this output?
ethane.pdb methane.pdb
ls *t*i.pdbls *t?ne.*ls *t??ne.pdbls ethane.*Solution
The solution is
3.
1.shows all files whose names incorporate nada or more than characters (*) followed past the lettert, then null or more characters (*) followed past1.pdb. This givesethane.pdb methyl hydride.pdb octane.pdb pentane.pdb.
2.shows all files whose names start with zippo or more characters (*) followed by the lettert, then a single character (?), thenne.followed by zero or more than characters (*). This will requite u.s.a.octane.pdbandpentane.pdbbut doesn't match annihilation which ends inthane.pdb.
iii.fixes the problems of pick 2 by matching two characters (??) betwixttandne. This is the solution.
four.only shows files starting withethane..
More on Wildcards
Sam has a directory containing calibration data, datasets, and descriptions of the datasets:
. ├── 2015-10-23-calibration.txt ├── 2015-10-23-dataset1.txt ├── 2015-10-23-dataset2.txt ├── 2015-10-23-dataset_overview.txt ├── 2015-10-26-calibration.txt ├── 2015-10-26-dataset1.txt ├── 2015-ten-26-dataset2.txt ├── 2015-10-26-dataset_overview.txt ├── 2015-xi-23-calibration.txt ├── 2015-11-23-dataset1.txt ├── 2015-11-23-dataset2.txt ├── 2015-11-23-dataset_overview.txt ├── backup │ ├── calibration │ └── datasets └── send_to_bob ├── all_datasets_created_on_a_23rd └── all_november_filesBefore heading off to another field trip, she wants to dorsum upward her information and send some datasets to her colleague Bob. Sam uses the post-obit commands to get the task done:
$ cp *dataset* backup/datasets $ cp ____calibration____ backup/scale $ cp 2015-____-____ send_to_bob/all_november_files/ $ cp ____ send_to_bob/all_datasets_created_on_a_23rd/Assist Sam past filling in the blanks.
The resulting directory construction should await similar this
. ├── 2015-10-23-scale.txt ├── 2015-ten-23-dataset1.txt ├── 2015-x-23-dataset2.txt ├── 2015-ten-23-dataset_overview.txt ├── 2015-10-26-scale.txt ├── 2015-ten-26-dataset1.txt ├── 2015-10-26-dataset2.txt ├── 2015-x-26-dataset_overview.txt ├── 2015-11-23-scale.txt ├── 2015-11-23-dataset1.txt ├── 2015-xi-23-dataset2.txt ├── 2015-xi-23-dataset_overview.txt ├── fill-in │ ├── scale │ │ ├── 2015-x-23-calibration.txt │ │ ├── 2015-x-26-calibration.txt │ │ └── 2015-xi-23-calibration.txt │ └── datasets │ ├── 2015-10-23-dataset1.txt │ ├── 2015-x-23-dataset2.txt │ ├── 2015-10-23-dataset_overview.txt │ ├── 2015-10-26-dataset1.txt │ ├── 2015-10-26-dataset2.txt │ ├── 2015-10-26-dataset_overview.txt │ ├── 2015-11-23-dataset1.txt │ ├── 2015-eleven-23-dataset2.txt │ └── 2015-11-23-dataset_overview.txt └── send_to_bob ├── all_datasets_created_on_a_23rd │ ├── 2015-ten-23-dataset1.txt │ ├── 2015-10-23-dataset2.txt │ ├── 2015-10-23-dataset_overview.txt │ ├── 2015-11-23-dataset1.txt │ ├── 2015-11-23-dataset2.txt │ └── 2015-11-23-dataset_overview.txt └── all_november_files ├── 2015-11-23-calibration.txt ├── 2015-11-23-dataset1.txt ├── 2015-xi-23-dataset2.txt └── 2015-eleven-23-dataset_overview.txtSolution
$ cp *calibration.txt fill-in/calibration $ cp 2015-11-* send_to_bob/all_november_files/ $ cp * -23-dataset * send_to_bob/all_datasets_created_on_a_23rd/
Organizing Directories and Files
Jamie is working on a project and she sees that her files aren't very well organized:
analyzed/ fructose.dat raw/ sucrose.datThe
fructose.datandsucrose.datfiles contain output from her data analysis. What command(s) covered in this lesson does she need to run so that the commands below will produce the output shown?Solution
Jamie needs to move her files
fructose.datandsucrose.datto theanalyzeddirectory. The crush will expand *.dat to match all .dat files in the current directory. Themvcommand and so moves the listing of .dat files to the 'analyzed' directory.
Reproduce a folder structure
Y'all're starting a new experiment and would like to indistinguishable the directory structure from your previous experiment then yous can add new data.
Assume that the previous experiment is in a folder called
2016-05-eighteen, which contains adatafolder that in turn contains folders namedrawandprocessedthat contain data files. The goal is to re-create the folder structure of the2016-05-xviiifolder into a folder called2016-05-20so that your final directory structure looks like this:2016-05-twenty/ └── data ├── processed └── rawWhich of the post-obit fix of commands would achieve this objective? What would the other commands do?
$ mkdir 2016-05-20 $ mkdir 2016-05-xx/data $ mkdir 2016-05-20/information/processed $ mkdir 2016-05-20/data/raw$ mkdir 2016-05-20 $ cd 2016-05-xx $ mkdir data $ cd data $ mkdir raw processed$ mkdir 2016-05-20/information/raw $ mkdir 2016-05-20/data/processed$ mkdir -p 2016-05-20/data/raw $ mkdir -p 2016-05-20/information/processed$ mkdir 2016-05-20 $ cd 2016-05-20 $ mkdir information $ mkdir raw processedSolution
The first ii sets of commands achieve this objective. The commencement set uses relative paths to create the top-level directory before the subdirectories.
The third set of commands will give an error considering the default behavior of
mkdirwon't create a subdirectory of a non-existent directory: the intermediate level folders must be created first.The fourth fix of commands achieve this objective. Remember, the
-poption, followed by a path of one or more directories, will causemkdirto create whatever intermediate subdirectories as required.The final set of commands generates the 'raw' and 'processed' directories at the same level as the 'information' directory.
Central Points
cp [old] [new]copies a file.
mkdir [path]creates a new directory.
mv [erstwhile] [new]moves (renames) a file or directory.
rm [path]removes (deletes) a file.
*matches zero or more characters in a filename, then*.txtmatches all files catastrophe in.txt.
?matches whatever single grapheme in a filename, and so?.txtmatchesa.txtmerely notany.txt.Apply of the Control key may be described in many means, including
Ctrl-Ten,Control-X, and^X.The beat out does non accept a trash bin: once something is deleted, it's really gone.
Near files' names are
something.extension. The extension isn't required, and doesn't guarantee anything, but is usually used to signal the type of information in the file.Depending on the type of work you do, you may need a more powerful text editor than Nano.
santistevanfitain.blogspot.com
Source: https://swcarpentry.github.io/shell-novice/03-create/index.html
0 Response to "How to Find Path and Upload Shel"
Post a Comment