Learn

Let’s work on a basic script that prints a directory structure in a tree format, which is useful for viewing nested subdirectories. The script takes advantage of the powerful commands that the Linux shell provides for file and folder operations.

We will be using conditional statements as well as the following commands:

  • echo
  • cd
  • pwd
  • ls
  • grep
  • sed
  • wc

This script will take in an optional string argument: the parent directory that should be the starting point for the tree. If this is not provided, we will use the current working directory. We will print a message if the parent directory has no subfolders to print. If we find there are subfolders to print, we’ll use a combination of the commands ls, grep, and sed to print the directory structure tree.

We will be working on the script named tree.sh, which is already opened in the editor.

Instructions

1.

Let’s begin by checking the tree.sh script to see if an input argument was provided. If so, we should change the current working directory to that argument.

In the code editor, where there’s a comment in the file, add a conditional statement that:

  • Checks if $1 was not equal to an empty string ""
  • If so, the script should cd to $1

Remember to use quotes around $1!

Click the Run button when you are done.

2.

After the conditional statement, use the pwd command to print out the current working directory.

Click the Run button when you are done.

3.

Next, use the following in a conditional statement to check if no subdirectories exist under the parent directory.

`ls -F -1 | grep "/" | wc -l` = 0
To see the logic behind the statement: The provided conditional statement uses `ls` lists files and directories with indicators one line at a time. `grep` is then used to find the `/` indicator which implies a directory. If the line count calculated by `wc -l` is `0`, then no subdirectories exist.

If the above statement is true, use echo to print " -> no sub-directories".

Click the Run button when you are done.

4.

After script is in the right directory, use the ls command with the -R option to print subdirectories recursively. This prints out all the files, categorized by the directories they are located inside.

Click the Run button when you are done.

5.

Run ./tree.sh ~ with the home (~) directory as the input argument.

Notice how the output includes all subdirectories but also all the files in those directories as well. We will filter out individual files and format the output in the next exercise!

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?