Bash Practices

Pragma

#!/bin/bash

Set variable

variableName="some string value"

See the value of the variable

echo "${variableName}"

Prompt and an input and set it to a variable

read variableName

If there is value, else …

if [ -n variableName ]; 
     then
         echo "your input is: ${variableName}"
     else 
         echo "There is no input entered" 
fi

If this text is equal to variable

if [[ "$variableName" == "some string value" ]]; then ... fi

Symlink

Folder: /usr/bin/, Link: ubin

$ ln -s /usr/bin/ ubin

Case Condition Example

#!/bin/bash

case EXPRESSION in 

  pattern-1)
    statement 
    ;;

  pattern-2) 
    statement
    ;;

  pattern-3 | pattern-4) 
    statement 
    ;;

  *)
    statement 
    ;; 
esac

Set Y/n with case condition

asks if the path is the default path, if not then asks the user inputs the new path value

path=/some/path

read -r -p "is this path right: $(path) ? [Y/n] " path_answer

case  $path_answer in
  [yY][eE][sS][yY])
    ;;
  [nN][oO][nN])
    read -r -p "Enter new path: " path;
    ;;
  *)
    echo "invalid input"
    exit 1
    ;;
esac

Case Condition Typical Help File

In the case of parameter given in command line for now.sh as an example:

case $1 in
    --help )
        echo "Usage: now [OPTION FLAG]"
        echo "  --help          shows this dialog then exits."
        echo "  -f | --full     full string, e.g. 20230423091532"
        echo "  -d | --dash     dash seperator, e.g. 2023-04-23-09-15"
        echo "  -D | --detailed  full, underscore seperator, e.g. 2023_04_23_09_15_32"
        echo "  -u | --unix     unix timestamp."
        ;;

    -f | --full )
        date +%Y%m%d%H%M%S
        ;;

    -d | --dash )
        date +%Y-%m-%d-%H-%M
        ;;

    -D | --detailed )
        date +%Y_%m_%d_%H_%M_%S
        ;;

    -u | --unix )
        date +%s
        ;; 

    *)
        date +%Y-%m-%d-%H-%M
        exit 1;
        ;;
esac

bc

bc – An arbitrary precision calculator language

$ echo "scale=3; 100/3" | bc
33.333

Array and For Loop

BOOKS=('The Book Title' 'Another Book Title')

# Loop in that array
for book in "$${BOOKS[@]} $"; do 
  echo "Book:$$book $"
done

Start the Discussion!Leave a Reply