DEV Community

Janak Shrestha
Janak Shrestha

Posted on

Creating Nested Directory Structures in Linux: A Guide to Using mkdir -p

The application development team needs some directories created on one of the app servers in Stratos Datacenter. They will use these directories to store some data. They have shared below requirements with us:

Create some directories as below under /opt directory on App server 2 in Stratos Datacenter.

/opt/app/backup/latest
Enter fullscreen mode Exit fullscreen mode

Solution

Step 1: Connect to App Server 2 (stapp02)

ssh steve@stapp02
# Password: Am3ric@
Enter fullscreen mode Exit fullscreen mode

Step 2: Switch to root

sudo su -
# Password: Am3ric@
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the directory structure

# Create the directory with parent directories
mkdir -p /opt/app/backup/latest
Enter fullscreen mode Exit fullscreen mode

Step 4: Verify the directory creation

# Check the directory exists
ls -la /opt/app/backup/latest

# Show the full path
ls -ld /opt/app/backup/latest

# Show the directory tree
ls -la /opt/app/
Enter fullscreen mode Exit fullscreen mode

One-Line Command

echo 'Am3ric@' | ssh steve@stapp02 "sudo -S bash -c 'mkdir -p /opt/app/backup/latest && ls -la /opt/app/backup/latest'"
Enter fullscreen mode Exit fullscreen mode

Expected Output

[root@stapp02 ~]# mkdir -p /opt/app/backup/latest

[root@stapp02 ~]# ls -la /opt/app/backup/latest
total 8
drwxr-xr-x 2 root root 4096 Jul 19 10:00 .
drwxr-xr-x 3 root root 4096 Jul 19 10:00 ..

[root@stapp02 ~]# ls -ld /opt/app/backup/latest
drwxr-xr-x 2 root root 4096 Jul 19 10:00 /opt/app/backup/latest
Enter fullscreen mode Exit fullscreen mode

Verification Commands

# Check full directory structure
ls -laR /opt/app/

# Verify each directory exists
test -d /opt/app && echo "✓ /opt/app exists" || echo "✗ /opt/app missing"
test -d /opt/app/backup && echo "✓ /opt/app/backup exists" || echo "✗ /opt/app/backup missing"
test -d /opt/app/backup/latest && echo "✓ /opt/app/backup/latest exists" || echo "✗ /opt/app/backup/latest missing"

# Check ownership and permissions
stat /opt/app/backup/latest
Enter fullscreen mode Exit fullscreen mode

Summary

  • Directory created: /opt/app/backup/latest
  • Parent directories created automatically with -p flag
  • Ownership: root:root
  • Permissions: drwxr-xr-x (755)

The required directory structure has been created successfully on App Server 2.

Top comments (0)