0

I have a script that would have multiple paths (folder names).

Each folder path would have a Dockerfile, but its uncertain at what level that file would exist.

Lets say my path is "v1/airflow/1.86/src/code/"

Bu the file can be at Like for eg "v1/airflow/1.86/src/Dockerfile" or it can be at "v1/airflow/1.86/Dockerfile"

so i am trying to figure out a way where i can take a step back or cd ../ check recursively if the file exist there, if not then go one directory back, and look again and if it does, stop looking further

Any help is appreciated

Mohammed Ali
  • 101
  • 1
  • Why not just use `basename` & `dirname`? – Bib Feb 06 '23 at 18:30
  • (1) `v1/airflow/1.86/src/code/` is a relative path. Should the search for `Dockerfile` stop after checking `v1/Dockerfile`? or after `./Dockerfile`? Or should it continue up to `/Dockerfile`? (2) What if the path was `foo/../bar/`? Should `foo/Dockerfile` be ever considered? If by "my path" you meant your current working directory then `..` should not appear; but `v1/airflow/1.86/src/code/` is relative to your current directory, it cannot be your current working directory, I guess `..` may appear. (3) What if there are symlinks in the path? ([compare this](https://superuser.com/a/1217241)). – Kamil Maciorowski Feb 08 '23 at 17:28

1 Answers1

0

A quick & dirty solution:

dirs=$(echo v1/airflow/1.86/src/code/ | tr '/' ' ')
path=""
for element in ${dirs[@]}
do
    if [[ -z "$path" ]]; then path=$element; else path="$path/$element"; fi
    printf "%s\n" "$path"
    [[ -e "${path}/Dockerfile" ]] && printf "Found it!\n"
done

This checks from the top down. Reversing the order of the array should not be too difficult.

doneal24
  • 633
  • 4
  • 10
  • What if the path already contains a space as a *legitimate* part of the name of some component? – Kamil Maciorowski Feb 08 '23 at 16:01
  • Yes, it will break if any component of the path has whitespace or newlines. A full-fledged solution is a bit harder. – doneal24 Feb 08 '23 at 16:20
  • "Reversing the order of the array should not be too difficult." – The only array here is what `for` sees. Your `dirs` is not an array. From `$()` you get exactly one string. `${dirs[@]}` *in this case* is equivalent to `$dirs`. It expands to multiple words, only because it's not double-quoted. I note the "quick & dirty" label. Dirty code is tolerable when it's potentially useful, but `${dirs[@]}` from not-an-array is an obfuscation, not even a useful dirt. My impression is that you truly planned `dirs` to be an array (otherwise you would just use `$dirs`). I'm letting you know it's not. – Kamil Maciorowski Feb 08 '23 at 18:36