Logo  

CS469 - Linux and Unix Administration and Networking

Displaying exercises/e5/solution/c.sh

#!/bin/bash

# Given a path on the command line, use stat to print the permissions, user and
# group for each path as you use dirname to walk back up the directory tree to
# root (/).
# Example output:
# > ./e.sh a.sh
# drwxr-xr-x   sbaker    users     4096 /net/sbaker/469/h/e5
# drwxr-xr-x   sbaker    users     4096 /net/sbaker/469/h
# drwxr-xr-x   sbaker    users     4096 /net/sbaker/469
# drwx--xr-x   sbaker    users     4096 /net/sbaker
# drwxr-xr-x     root     root     4096 /net
# drwxr-xr-x     root     root     4096 /

# Get the path from the first command line argument, if it is not provided, use
# the current working directory (.):
path=${1:-.}

# Use realpath to get the real path:
path=$(realpath "$path");

# If the path isn't to a directory, use dirname to get the directory name:
if [[ ! -d "$path" ]]; then
  path=$(dirname "$path");
fi

# While the path is not equal to /, loop:
while [[ $path != / ]]
do
  # Print the permissions, username, groupname, size and path using the stat
  # command.
  stat -c "%A %8U %8G %n" "$path"

  # Use dirname to go up one directory:
  path=$(dirname "$path");
done

# Print out / the same as with the other directories:
stat -c "%A %8U %8G %n" "$path"