The main problem:
Write a script that determines a path's depth relative to the filesystem's root. The path is received as an argument on the command line. If no argument is received, the current working directory is considered as the path. If the argument is not a valid path, then an error message is printed to stderr and a non-zero exit status is returned. Other error conditions, such as insufficient permissions to read the given path should be treated in a similar manner. If successful, the script should print the depth to stdout and return 0.
I know how to deal with the error cases, but my main problem is to find the depth of the path. I was thinking to save the given path as a string and to count the number of '/' apparitions. I saw that I can do that using this command:
grep -o "/" $PWD | wc -l
But this displays 1 even if I change multiple directories. I am still learning about shell scripting, so can you give me details about the solutions?
zsh
/ksh
/yash
/bash
with that<<<
here-string operator. You could use a here-document orprintf '%s\n' "$PWD" | grep -o / | wc -l
to make it more portable. In any case,-o
is a GNUgrep
extension). – Stéphane Chazelas Jan 26 '18 at 15:15