for dir in ${paths[@]}
    val=`mkdir -p ${newpath}/${newdir}`
    echo ${val}

    for file in "${dir}"/*; do
        if [[ -f $file && $file = *.@(c|cc|cpp|h) ]]; then
            cp ${file} ${val}

I want to loop through the directories and copy the filenames in the newly created val directory..but I am unable to print the value of val. What am I doing wrong?

  • 1
    You seem to treat $paths as an array in ${paths[@]}, but you populate it with a single value: paths=$1.
    – choroba
    Aug 13 '21 at 9:21
  • ohh but there will be multiple paths assigned like this Path1: /home/demo/path0 PATH2: /home/demo/path1 PATH3: /home/demo/path2 Aug 13 '21 at 10:38
  • 1
    That's just a string, not an array. Array is declared in this way: paths=(/home/demo/path0 /home/demo/path1 /home/demo/path2).
    – choroba
    Aug 13 '21 at 12:08
  • 1
    @user6690412 I see you accepted an answer but that answer isn't actually related to your main problem and doesn't address your other problems. Copy/paste your script into shellcheck.net, fix the problems it tells you about, and then ask a new question if you still need help but this time show us how you're calling your script too as that is the key to solving your main problem (i.e. how to populate paths and files correctly).
    – Ed Morton
    Aug 13 '21 at 15:19
  • Always paste your script into https://shellcheck.net, a syntax checker, or install shellcheck locally. Make using shellcheck part of your development process.
    – waltinator
    Aug 22 '21 at 16:52

You're assigning the output of

mkdir -p ${newpath}/${newdir}

to val, however this command does not output anything, thus you can't print anything. (You can, but the output is empty)

If you want to have anything in val, do it first and use val to create the directory, like:


mkdir "$val"

this way you have the created directory in your variable.

  • Thank you.. this worked, but however, it only creates one directory..while I have mentioned multiple directories in the paths variable. Aug 13 '21 at 11:00
  • 1
    @user6690412 $paths is not an array (even though you're trying to treat it as one on line 3 of your script), it can hold only one value. you've set it to "$1", the first argument to the script.
    – cas
    Aug 13 '21 at 14:22
  • 1
    newpath is an array so using it like a scalar is wrong even though it'll "work" as bash will treat it like the first element of the array. This just addresses one of the many problems in the OPs script, though, and after fixing this part the OPs script still won't be close to working.
    – Ed Morton
    Aug 13 '21 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.