About
Various testing on conditional events or variables (exit test, variable defaults).
Last Command Return Value
if [ $? -eq 0 ]; then
echo "Success"
else
echo "Failure"
if [ $? -ne 0 ]; then
echo "Failure"
else
echo "Success"
Conditionally Exit
# Use braces
CARLA_TARBALL=`ls ${CARLA_ROOT}/Distd/*.tar.gz 2> /dev/null` || { echo "Carla tarball not found, exiting." ; exit 1; }
Conditionally Set Variables
This one is obscure....<TODO> explain!
Copy Selected Files
cp --parents `find -name .pydevproject` /target_directory/
Docker
docker container inspect ecl >/dev/null 2>&1
if [ $? -ne 0 ]; then
groot-rocker-workspace --colcon --name ecl --bind /mnt/mervin/workspaces/devel/ecl:/mnt/ecl --work-directory /mnt/ecl ubuntu:22.04
else
docker container start -i ecl
fi
Random
# random number between 1 and 3
echo $((1 + $RANDOM % 3))
Install Packages
install_package ()
{
PACKAGE_NAME=$1
# Does not work if the package has been installed and later removed
# dpkg -s ${PACKAGE_NAME} > /dev/null
dpkg-query -W -f='${Status}' ${PACKAGE_NAME} | grep -q -P '^install ok installed$'
if [ $? -ne 0 ]; then
sudo apt-get -q -y install ${PACKAGE_NAME} > /dev/null
else
pretty_print " $(padded_message ${PACKAGE_NAME} "found")"
return 0
fi
if [ $? -ne 0 ]; then
pretty_error " $(padded_message ${PACKAGE_NAME} "failed")"
return 1
fi
pretty_warning " $(padded_message ${PACKAGE_NAME} "installed")"
return 0
}
# usage
install_package ansible