🎓 A1Learner
🔍
0 of 47 lessons completed

Bash File Commands

File commands create, copy, move and delete files. Bash can also test whether a file exists.

Create a file with touch

The touch command creates an empty file. The ls command shows the new file name.

touch notes.txt
ls notes.txt

Copy a file with cp

The cp command makes a second file with the same content. Both file names exist after the copy.

touch notes.txt
cp notes.txt copy.txt
ls notes.txt
ls copy.txt

Rename a file with mv

The mv command gives a file a new name. The old name is gone after the move.

touch old.txt
mv old.txt new.txt
ls new.txt
if [ -f old.txt ]; then
  echo "old still exists"
else
  echo "old is gone"
fi

Example

touch draft.txt
cp draft.txt backup.txt
mv draft.txt final.txt
rm backup.txt
if [ -f final.txt ]; then
  echo "final exists"
else
  echo "final missing"
fi
if [ -f backup.txt ]; then
  echo "backup exists"
else
  echo "backup missing"
fi

Key points

  • Use touch to create an empty file.
  • Use cp to copy a file to a new name.
  • Use mv to rename a file to a new name.
  • Use rm to delete a file.
  • Write [ -f notes.txt ] to test whether a file exists.

In this example, touch creates draft.txt and cp copies it to backup.txt. The mv command renames draft.txt to final.txt. The rm command deletes backup.txt, and the two tests prove the final state.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command renames old.txt to new.txt?