1
\$\begingroup\$

In this post, I present the bash script for installing the ds4mac:

#!/usr/bin/env bash

script_magic="alias ds='source ~/.ds/ds_script'"

echo "Installing ds..."

grep "$script_magic" ~/.bashrc 

if [ $? != 0 ]; then
    echo "$script_magic" >> ~/.bashrc   
    echo "~/.bashrc updated!"
else
    echo "~/.bashrc is already updated."
fi

# Create files:
echo "Creating files..."
mkdir -p ~/.ds
echo "Created the .ds directory."
make > /dev/null
cp ds_engine ~/.ds/ds_engine
echo "Built the ds_engine."
tag_file=~/.ds/tags
touch $tag_file

add_tag_to_file () {
    grep $1 $tag_file > /dev/null
    if [ $? != 0 ]; then
        echo $1 $2 >> $tag_file
        echo Setting the tag $1 to directory $2 done.
    fi
}

# Populate the default 
echo "Populating the tag file with default tags..."

add_tag_to_file "docs" "~/Documents"
add_tag_to_file "down" "~/Downloads"
add_tag_to_file "root" "/"
add_tag_to_file "home" "~"
add_tag_to_file "ds"   "~/.ds"

echo "Done populating the tag file with default tags."
echo "Copying the script..."

cp ds_script ~/.ds/ds_script

echo "Done! ds will be available for use in your next shell session. :-]"

(The entire project is here.)

See also

  1. The main script
  2. The tag engine

Critique request

Please, tell me anything that comes to mind. ^^

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

The installer script should not ignore errors. As an example, in

make > /dev/null
cp ds_engine ~/.ds/ds_engine

the make command can fail (if no compiler is installed, if there are syntax errors in the program, etc.). In such a case it makes no sense to copy the binary to the installation directory, or to execute any of the subsequent commands. That will only produce more error messages which hide the actual problem.

A simple solution is to set the "-e" flag in the script:

#!/usr/bin/env bash
set -e

From "man bash" (this applies to other shells as well):

-e      Exit immediately if a simple command ... exits with a non-zero status
\$\endgroup\$
2
\$\begingroup\$

Patterns like:

grep $1 $tag_file > /dev/null
if [ $? != 0 ]; then 
  ...
fi

Can be rewritten as:

if grep -q $1 $tag_file; then
  ...
fi
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.