user7437554
user7437554

Reputation:

cd to multiple directories in a shell script

I am making a script named Big_script.sh to access two directories called A and B, inside them i need to access three directories called A1, A2, A3; B1, B2, B3 (respectively). Once in there, i need the script to run another script with sh small_script.sh.

Is it possible to do something like this in Big_script:

cd */*
sh small_script.sh

or is there any way to do that in a shell script or in python that could help? because it is not working

Upvotes: 0

Views: 1260

Answers (1)

You cannot cd to more than one directory at a time (so you need to come back to the original directory, if the path to cd is relative). It is not a limitation of the shell but a property of unix processes (so coding in some other language like Python or C won't change much); they each have only one current directory (and the shell runs the chdir(2) system call for its cd builtin)

You might consider computing the full path (using realpath(1)) of every directory, and storing that path in some shell variable. Then you could cd in a loop.

Some shells have a stack of directories, which you could manipulate with pushd & popd. In that case, you might code

for d in */* ; do
  pushd "$d"
  sh small_script
  popd
done

You need to be sure that the globbing expansion of */* gives only directories. With zsh you might code */*(/) to expand only directories. See glob(7) & path_resolution(7) & credentials(7).

If your shell don't have pushd you could try

for d in $(realpath */*); do
  cd "$d" && sh small_script.sh
done

or using a subshell

for d in */*; do
  (cd "$d" && exec small_script.sh)
done

See this for more about pushd & popd

Notice that if you do cd a/b followed later by cd e/f the shell is trying to go (for the second cd) into the a/b/e/f directory (which probably do not exist) because e/f is a relative path (so interpreted in the context of the previous current directory a/b). You might want cd a/b followed by cd ../../e/f ...

Take time to understand why cd needs to be a shell builtin. Perhaps read Advanced Linux Programming.

See also find(1). It might be more useful (with its -exec action).

BTW, it could be simpler to change your small_script to accept as argument the directory in which it should go. Then that script might start with cd "$1".

Upvotes: 1

Related Questions