1

This is the code I have:

#!/bin/bash
FILES=~/Desktop/cpp/$1/*
mkdir ~/Desktop/cpp/$1o 
for f in $FILES
do
    echo $(basename $f) >>  ~/Desktop/cpp/$1err.log
    g++ '"'$f'"' -std=c++11 -o '"'~/Desktop/cpp/$1o/$(basename "$f").out'"' 2>>  ~/Desktop/cpp/$1err.log
done

If I don't use '"' parts, then the script works fine for files without spaces. With them, it says:

usr/bin/ld: cannot open output file /dirname/-
x.out: No such file or directory

How do I add quotation marks around the file name so that spaces are supported?

0

2 Answers 2

2

You need to quote the variables with double quotes, not '"' literal double quote strings, just plain "$f" double quotes. See Security implications of forgetting to quote a variable in bash/POSIX shells for all the gory details.

And I'd use more variables to reduce duplication.

Try this:

#!/usr/bin/env bash
cppdir="$HOME/Desktop/cpp/$1"
if [[ ! -d "$cppdir" ]]; then
    echo "No such directory" >&2
    exit 1
fi

outdir="${cppdir}o"
mkdir -p "$outdir"

errlog="${cppdir}err.log"

for f in "$cppdir"/*; do
    b=$(basename "$f")
    printf '%s\n' "$b" >> "$errlog"
    g++ "$f" -std=c++11 -o "$outdir/$b.out" 2>> "$errlog"
done
2
  • Thanks. I tried using "s first, but it didn't work. Your code works though. I'm not sure why. I wrote: g++ "$f" -std=c++11 -o "~/Desktop/cpp/$1o/$(basename "$f").out" 2>> ~/Desktop/cpp/$1err.log Commented Oct 3, 2020 at 17:47
  • When you put the tilde inside quotes, it doesn't expand. Commented Oct 3, 2020 at 21:01
0

A standard way is to use find and xargs with a NUL-character as delimiter:

outdir="$1"o
mkdir "$outdir"
errlog="$1"err.log
touch "$errlog"

find ~/Desktop/cpp/"$1"/ -type f -name '*.cpp' -print0 |
  xargs -0 -I source bash -c "echo source >> $errlog &&
    g++ source -std=c++11 -o source.out 2>> $errlog"
1
  • Thank you. I hadn't tried checking extensions yet. Commented Oct 3, 2020 at 17:50

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.