/
Conditionals

Conditionals



About

Various testing on conditional events or variables (exit test, variable defaults).

Last Command Return Value

Make sure you have spaces inside the [] otherwise bash will spit the dummy!


Check for Success
if [ $? -eq 0 ]; then
  echo "Success"
else
  echo "Failure"


Check for Failure
if [ $? -ne 0 ]; then
  echo "Failure"
else
  echo "Success"

Conditionally Exit

Exit with Error in 1-Line
# Use braces
CARLA_TARBALL=`ls ${CARLA_ROOT}/Distd/*.tar.gz 2> /dev/null` || { echo "Carla tarball not found, exiting." ; exit 1; }

Conditionally Set Variables

Set if not already defined
: ${var=value}

This one is obscure....<TODO> explain!

Set if not defined OR set to the empty string
: ${var:=value}

Copy Selected Files

Recursively Copy Selected Files with Folder Structure
cp --parents `find -name .pydevproject` /target_directory/

Docker

Check if docker container with specified name exists
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

Recursively Copy Selected Files with Folder Structure
# random number between 1 and 3
echo $((1 + $RANDOM % 3))

Install Packages


Install packages via sudo only if it is not already installed
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


Related content

Args
More like this
VirtualEnv
VirtualEnv
More like this
Docker
More like this
Konsole
More like this
Environment Hooks
Environment Hooks
More like this
Actions
More like this