Learn Bash - More Commands & Options

Question Click to View Answer

Create the directory ~/Desktop/cq/.

mkdir ~/Desktop/cq/

Create the files file1, file2, and file3 in the ~/Desktop/cq directory.

cd ~/Desktop/cq/
touch file1 file2 file3

The touch program makes multiple files when it's supplied with multiple arguments.

Create the ~/Desktop/cq/huh directory and move file1 and file3 into the huh directory.

cd ~/Desktop/cq/ # not needed if you are already in the right directory
mkdir huh
mv file1 file3 huh/

Append the text "I am file 2" to the file2 file.

Then move the file2 into the ~/Desktop/cq/huh directory and rename it to be really_cool.

Check that the really_cool file still has the content "I am file 2".

cd ~/Desktop/cq/
echo "I am file 2" >> file2
mv file2 huh/really_cool
cat huh/really_cool

The mv command can be used to move and rename files. In this example, mv moves file2 to the huh/ directory and renames it to be really_cool.

Copy file1, really_cool, and file3 from the ~/Desktop/cq/huh directory to the ~/Desktop/cq/www directory.

cd ~/Desktop/cq/
mkdir www
cp huh/file1 huh/really_cool huh/file3 www/

Create the file ~/Desktop/cq/file1 and add the text "I will clobber" to the file. Copy file1 to the www directory and explain what happened to the original ~/Desktop/cq/www/file1.

cd ~/Desktop/cq/
echo "I will clobber" >> ~/Desktop/cq/file1
cp file1 www/

The original ~/Desktop/cq/www/file1 was silently clobbered meaning it was replaced and there was no warning message.

Create the file ~/Desktop/cq/bob. Then rename the file to be ~/Desktop/cq/fred.

cd ~/Desktop/cq/
touch bob
mv bob fred

The mv program is used to rename files.

Use the -l option to provide a long listing of all the files in the ~/Desktop/cq/ directory.

ls -l ~/Desktop/cq/

Options adjust the behavior of programs, so they can be tailored for a variety of purposes. In this example, the -l option is used to make the ls command provide additional information about the files in a directory.

Use the -l and -F options to provide a long listing of all files in the ~/Desktop/cq/ directory and distinguish between regular files and folders.

ls -lF ~/Desktop/cq/

Multiple options can be written separately (ls -l -F ~/Desktop/cq/), but it's more common to group them together.

Create the ~/Desktop/cq/bar file. Use the -i (interactive) option and delete the ~/Desktop/cq/bar file.

cd ~/Desktop/cq/
touch bar
rm -i bar

The interactive option displays a prompt and forces the user to type 'yes' before deleting the file.

Delete the ~/Desktop/cq/ directory and all of its contents.

cd ~/Desktop/
rm -r cq/

The -r option recursively deletes everything in a folder, including all subfolders and files. rm -r is a dangerous command because it will delete large portions of the filesystem if instructed. Use this command with caution and make sure you don't have any typos.