Linux and Bash course menu
Linux File Commands: mkdir, touch, cp, mv and rm
Create folders and files with mkdir and touch, copy and move with cp and mv, delete safely with rm, use wildcards, and edit text files with nano.
On this page
Create folders#
mkdir makes a folder. -p creates parent folders too, and does not complain if they exist:
mkdir project
mkdir -p project/src/utils
tree projectproject
└── src
└── utils
3 directories, 0 filesCreate files#
touch creates an empty file, or updates the time of an existing one. echo with > writes text to a file:
cd project
touch README.md
echo "print('hi')" > src/app.py
ls -l srctotal 8
-rw-rw-r-- 1 asha asha 12 Nov 5 06:26 app.py
drwxrwxr-x 2 asha asha 4096 Nov 5 06:26 utilsTo edit a file in the terminal, the easiest editor is nano:
nano README.mdType your text, press Ctrl+O then Enter to save, and Ctrl+X to leave. The commands are listed at the bottom of the screen. On servers, you may also meet vim: press i to type, then Esc, then :wq to save and leave, or :q! to leave without saving.
Copy#
cp source destination copies a file:
cp src/app.py src/app_backup.py
ls srcapp.py
app_backup.py
utilsTo copy a folder, add -r (recursive):
cp -r src src_copy
lsREADME.md
src
src_copyMove and rename#
mv does both. Linux has no separate rename command for everyday use:
mv src/app_backup.py backup.py
mv backup.py old.py
lsREADME.md
old.py
src
src_copyDelete#
rm removes files. rmdir removes empty folders, and rm -r removes a folder and everything in it:
rm old.py
rm -r src_copy
lsREADME.md
srcrm -i asks before each deletion, and cp -i and mv -i ask before overwriting. By default, cp and mv overwrite without asking.
Wildcards#
The shell expands wildcards into matching names before the command runs.
ls *.png
ls a?.png
ls [ab]1.png
echo *.txta1.png
a2.png
b1.png
a1.png
a2.png
a1.png
b1.png
notes.txtecho shows what the shell produced, which makes it a safe way to test a pattern.
Brace expansion#
Braces produce a list of words, whether or not such files exist:
mkdir -p site/{css,js,images}
ls site
echo photo{1..3}.jpgcss
images
js
photo1.jpg photo2.jpg photo3.jpgNames with spaces#
Use quotes, or a backslash before the space:
touch "my file.txt"
ls -l my\ file.txt-rw-rw-r-- 1 asha asha 0 Nov 5 06:26 my file.txtCommon mistakes#
Practice#
Practice exercise
Create shop/products and shop/orders with one command, add an empty file orders/june.csv, copy it to orders/july.csv, and print the tree.
Show solution
mkdir -p shop/{products,orders}
touch shop/orders/june.csv
cp shop/orders/june.csv shop/orders/july.csv
tree shopshop
├── orders
│ ├── july.csv
│ └── june.csv
└── products
3 directories, 2 filesKey takeaway#
Next: Reading Files.
Finished this lesson?