0

I wrote a shell script (for practice) that should compile a C++ (.cpp) file, automatically generate an executable with clang++ and execute it. My code:

#!/bin/bash

function runcpp() {
  CPPFILE=$1
  if [ -z $CPPFILE ]; then
    echo "You need to specify a path to your .cpp file!"
  else
    echo -n "Checking if '$CPPFILE' is a valid file..."
    if [[ $CPPFILE == "*.cpp" ]]; then
      echo -e "\rChecking if '$CPPFILE' is a valid file... successful"
      echo -n "Generating executable for '$CPPFILE'..."
      clang++ $CPPFILE
      echo -e "\rGenerating executable for '$CPPFILE'... done"
    fi
  fi

}

It's not done yet, however, at line 9 (if [[ $CPPFILE == "*.cpp" ]]; then) something goes wrong: the script exits, even though the file I specified is a .cpp file. My Terminal window:

kali@kali:~$ ls -lha *.cpp
-rw-r--r-- 1 kali kali 98 Feb  9 19:35 test.cpp
kali@kali:~$ runcpp test.cpp 
Checking if 'test.cpp' is a valid file...kali@kali:~$
Dudek
  • 54
  • 1
  • 7
  • When you quote a pattern on the right-hand side of `==`, it loses it's meaning and is treated as a literal string. You want `[[ $CPPFILE == *".cpp" ]]` – glenn jackman Feb 09 '20 at 20:22
  • Get out of the habit of using ALLCAPS variable names, leave those as reserved by the shell. One day you'll write `PATH=something` and then [wonder why your script is broken](https://stackoverflow.com/q/28310594/7552). – glenn jackman Feb 09 '20 at 20:22
  • You've got a bug on `if [ -z $CPPFILE ]` -- either use `[[...]]` or quote the variable. – glenn jackman Feb 09 '20 at 20:23
  • @glennjackman: either that or use `case` to compare `$CPPFILE` with a pattern. – Arkadiusz Drabczyk Feb 09 '20 at 20:24
  • Also, just matching the pattern of the variable does not make it a valid file. You probably want `if [[ $cppfile == *".cpp" && -r $cppfile ]]` to check if you can read it. – glenn jackman Feb 09 '20 at 20:24
  • @glennjackman : Actually, quoting is unnecessary here and just makes the whole thing look unnecessarily complicted. `[[ $CPPFILE == *.cpp && .... ]]` would do as well. – user1934428 Feb 10 '20 at 07:32

0 Answers0