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ドル/
-
1\$\begingroup\$ Thanks. I can see a few things that would get picked up by shellcheck.net \$\endgroup\$chicks– chicks2020年05月29日 00:24:53 +00:00Commented May 29, 2020 at 0:24
1 Answer 1
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ドル