3
\$\begingroup\$

It's a pretty simple script really. I just want to know if there is a way to improve it.

#!/bin/env sh

set -o nounset
set -o errexit

if [[ "$#" -ne 3 ]] && [[ "$#" -ne 2 ]];
then
    echo "Usage: ./project.sh [NAME] [GENERATOR] [MAKEFILES]"
    exit 1
fi


mkdir $HOME/Dev/$1
mkdir $HOME/Dev/$1/src/
mkdir $HOME/Dev/$1/build/
cp $HOME/ProjectSetup/CMakeLists.txt $HOME/Dev/$1/

sed -i "s/set(CMAKE_PROJECT_NAME placeholder/set(CMAKE_PROJECT_NAME $1/" $HOME/Dev/$1/CMakeLists.txt

git init $HOME/Dev/$1/
cat > $HOME/Dev/$1/.gitignore << EOL
build/
compile_commands.json
.vscode/
EOL

touch $HOME/Dev/$1/src/main.cpp
cat > $HOME/Dev/$1/src/main.cpp << EOL 

int main(int argc, const char* argv[])
{
    
    return 0;
}
EOL

if [[ "$#" -eq 3 ]];
then
    cmake -G "$2 - $3" -S $HOME/Dev/$1 -B $HOME/Dev/$1/build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=1
else
    cmake -G "$2" -S $HOME/Dev/$1 -B $HOME/Dev/$1/build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=1
fi
ln -s $HOME/Dev/$1/build/compile_commands.json $HOME/Dev/$1/

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thanks. I can see a few things that would get picked up by shellcheck.net \$\endgroup\$ Commented May 29, 2020 at 0:24

1 Answer 1

3
\$\begingroup\$

Variables

It is a good practice to give meaningful names to the built-in option variables ($1, etc.):

if [[ "$#" -ne 3 ]] && [[ "$#" -ne 2 ]];
then
    echo "Usage: ./project.sh [NAME] [GENERATOR] [MAKEFILES]"
    exit 1
fi

name=$1
generator=$2

When they are used later in the code, you don't have to remember what the option order on the command line was.

DRY

$HOME/Dev/$1 is repeated numerous times in the code. Create a new variable and use that everywhere:

dev_dir=$HOME/Dev/$name

There is no need for 3 mkdir commands if you use the -p option to automatically create parent directories:

mkdir -p $dev_dir/src
mkdir -p $dev_dir/build

You can even do it all with one command using shell wildcard expansion:

mkdir -p $dev_dir/{build,src}

Although, that is arguably less readable than the 2 commands.

Simpler

The touch command should not be necessary since the cat with output redirect will create the main.cpp file if it does not exist.

Style

Usually, the trailing / can be omitted from directory paths, such as:

git init $HOME/Dev/$1/

It is cleaner like:

git init $HOME/Dev/$1
\$\endgroup\$

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.