0

I am rather new to programming, and completely new to BASH. As described in the title, I am trying to loop through the current directory and store the files ending with .cpp into an array. I also am trying to create a second array which replaces the ".cpp" suffix with ".o" Whenever I try to compile I get "syntax error in conditional statement"

x=0
cwd=$(pwd)
for i in $cwd; do
  if [[ $i == *.cpp]]
  then
    cppfield[$x] = $i
    ofield[$x] = field[$x] | sed s/.cpp/.o/
    x=$((count+1))
  fi
done 

2 Answers 2

1

Use:

shopt -s nullglob # In case there are no matches
for i in *.cpp; do
    ...
done

In your code, you're just setting i to $cwd, not the files in the directory.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure what's your purpose of doing this. But if you just want to generate file name that replaces .cpp with .o, it can be done in a much easier way

for f in *.cpp
do
    echo ${f/.cpp/.o}
done

1 Comment

I'd use "${f%.cpp}.o" -- with the "%" (meaning "remove this from the end") instead of "/" (meaning replace the first occurrence of) in case the filename contains ".cpp" somewhere other than the end, and double-quotes in case it contains spaces or other shell metacharacters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.