Bash constructs

From NoskeWiki
Jump to: navigation, search

About

NOTE: This page is a daughter page of: Unix


Here are some common bash constructs:


Bash constructs

User Prompt Statement

read -p "Enter your name: " NAME
printf "Hi $NAME \n"

If/Else Statement

read -p "Are you sure you want to continue this script [y/n]? " -n 1 -r
echo ''
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
  echo 'Then we will exit this script....'
  exit 1
else
  echo 'Then we will continue....'
fi
echo 'Hold onto hats'

Switch / Case Statement

read -p "Select option [1-2]: " ANSWER
case "$ANSWER" in
  [1]*)
    printf "You pressed 1\n"
    printf "You are fabulous\n"
    ;;
  [2]*)
    printf "You pressed 2\n"
    ;;
esac


For Loop

FILENAME_PREFIX=scores
VAL_MIN=0
VAL_MAX=1000
VAL_STEP=100
 
NUM_LOOPS=$[($VAL_MAX-$VAL_MIN)/$VAL_STEP]
echo "NUM_LOOPS = $NUM_LOOPS"
for ((i=0; i<$NUM_LOOPS; i++)); do
  min_val=$[$i * $VAL_STEP + $VAL_MIN]
  max_val=$[($i+1) * $VAL_STEP + $VAL_MIN]
 
  OUTPUT_FILE=${FILENAME_PREFIX}_${min_val}-${max_val}.txt
 
  echo "min_val = $min_val OUTPUT_FILE = $OUTPUT_FILE"
done
 
# OUTPUT:
#   min_val = 0 OUTPUT_FILE = scores_0-100.txt
#   min_val = 100 OUTPUT_FILE = scores_100-200.txt
#   min_val = 200 OUTPUT_FILE = scores_200-300.txt
#   ...

See Also


Links