I am working on a shell script (shell used, its version and OS are below). The script runs commands in a local git repository/directory with has several tags. The script outputs some string from greping files in a certain directory which is selected based on the repository tag name.
zsh --version
zsh 5.9 (x86_64-apple-darwin22.0)
OS: System Version: macOS 13.6.3
+
using oh-my-zsh, https://ohmyz.sh/
The script changes directory (cd
command) to the git local repository. Then it gets the tags in an array by MY_ARRAY=($(git tag))
. Then for each repository tag it does git checkout $my_tag --quiet
to that tag. Then cd
in one of the directories (directoryA) of the repository. Now it issues a pwd
to check the working directory; the output is /git-repository/directoryA
. At this moment the pwd
output is as expected (/git-repository/directoryA
). Now, while in /git-repository/directoryA
, the script does LIST_OF_SUBDIRECTORIES=($(ls -d */))
to get the array of the sub-directories of directoryA
; the output is LIST_OF_SUBDIRECTORIES is cw-events/ cw-metric-alarm/ eventbridge-scheduler/ msk/ secrets-manager/ ses/ sns-topic/ sqs/ ssm-params/ xlate/
. Now for each of this subdirectories (a for
loop is used), the script SHOULD cd
to a subdirectory in the array LIST_OF_SUBDIRECTORIES like this:
if echo "$my_tag" | grep -q -E "$MY_SUBDIRECTORY"; then
echo "MY_SUBDIRECTORY is $MY_SUBDIRECTORY"
set -x
cd $MY_SUBDIRECTORY 2>&1 | tee -a log_file.txt
set +x
echo "PWD Working Directory is $(pwd)"
The output of echo "MY_SUBDIRECTORY is $MY_SUBDIRECTORY"
is MY_SUBDIRECTORY is cw-events/
; the if condition is true so I would expect for the script to cd
in cw-events/
but the above echo "PWD Working Directory is $(pwd)"
is outputing /git-repository/directoryA
.
The script starts with #!/bin/zsh
. Trying in #!/bin/bash
I receive some errors.
I found some other questions on https://blog.kubesimplify.com/how-to-change-directory-in-shell-scripts or Script to change current directory (cd, pwd) but actually I do not want the directory to be changed in the parent shell but in the child shell.
Why the script while in /git-repository/directoryA
does not cd
in /git-repository/directoryA/subdirectory-of-A
?
Example of output:
The example I can give fast is the output of running the script:
FIRST-SUB-Directory is /git-repository/directoryA
LIST_OF_SUBDIRECTORIES is cw-events/ secrets-manager/ sqs/ ssm-params/
MY_SUBDIRECTORY is cw-events/
+/path/to/script/script.sh:44> cd cw-events/
+/path/to/script/script.sh:44> tee -a log_file.txt
+/path/to/script/script.sh:45> set +x
PWD Working Directory is /git-repository/directoryA
Thank you.