Why doesn't this Bash shell compile directories?

Hello I'm having a problem trying to get this Bash shell program to function properly.

Purpose: In the current directory, more into the sub-directories and compile the .c files.

Heres my code:

#!/bin/bash
 
wd=$(pwd)
for i
do
 cd ${i}
 gcc *.c
 cd $wd
done

Then I save it as myshell

Then I use

chmod u+x myshell

to compile it.

Then I use $ myshell to run it, it runs but doesn't compile the .c files...

I'm out of ideas, the code is from the textbook so it should work.

If you don't provide any arguments to that script, the for-loop has no list on which to iterate.

On an unrelated topic, if there is any chance of whitespace in the directory pathnames, quote wd and i when you reference them.

Regards,
Alister

1 Like

Thanks for the reply. I understand that I need to pass an argument now, however I'm not 100% sure how to do it.

Because I'm not sure how many directories may be in the current directory, I can't manually specify them as arguments. Reading I found the args=("$@") would this work? I tried putting it in my code but I don't know if its correct. Could anyone give me a link to a similar example please?

You could use find . -type d to create a list of subdirectories of your current dir. Or use ls and check the result with e.g. [ -d ... ]

A loop like this perhaps:

for DIR in ./*
do
        [ -d "$DIR" ] || continue # Ignore non-directories
        cd "$DIR" || continue # Ignore if can't cd
        gcc whatever
        cd ..
done

In case you were commenting on the absence of a list, a bare for i is fine, since it defaults to in "$@" .

Regards,
Alister

Thanks for the replys.

How would I make the argument the current working directory?

I thought

wd=$(pwd)

was the argument? The examples I have don't say anything about adding any extra code, and shoudl work, but obviously not..

I think this will achieve what you have asked for. However, I'm not sure that what you asked for is what you want.

Create the script (I'm using Bourne shell because there is nothing that needs the heavy duty of bash):

        cat > 223697.sh
#! /bin/sh
#       223697.sh - compile (contents of) directories


        dirs=`find . -mount -maxdepth 1 -mindepth 1 -type d`

        for dir in $dirs
        do
                cd $dir
                gcc *.c
                cd ..
        done

^D

NB the next step does NOT compile anything; it simply makes it executable.

chmod u+x 223697.sh

NB Do NOT type a dollar-sign ($) to run it. Just enter:

./223697.sh

This will compile all the C code in all the subdirectories. However,

I'm not sure if you really want 'gcc *.c', but that's what your code had.

1 Like

Thanks very much for replying, that is exactly what I wanted. I managed to get the BASH one working awsell but can't post the code up just atm.

Cheers for the help guys :b: