Shell: Misc Commands

(Last Updated On: )

In this tutorial I will show a few useful commands when working with linux shell.

Check Directory Exists:

  1. if [ -d /opt/test/ ]; then
  2. echo 'Directory Exists'
  3. fi

Check Directory Not Exists:

  1. if [ ! -d /opt/test/ ]; then
  2. echo 'Directory Does Not Exist'
  3. fi

Check File Exists:

  1. if [ -f /opt/test/test.log ]; then
  2. echo 'File Exists'
  3. fi

Check File Not Exists:

  1. if [ ! -f /opt/test/test.log ]; then
  2. echo 'File Does Not Exist'
  3. fi

Lowercase Variable:

  1. val='TEXT'
  2. echo "${val,,}"

Echo Variable:
This will print the value of “test”. Notice we use double quotes.

  1. test='My Test Val'
  2. echo "$test"

Echo String:

  1. echo 'My test string'

Split:
This will split on the comma into an array list and then loop through it.

  1. test='test 1,test 2'
  2. split_test=(${test//,/ })
  3.  
  4. for val in "${split_test[@]}"
  5. do
  6. echo $val
  7. done

Date:
This will print the date in the format YYYY-MM-dd

  1. my_date="$(date +Y-%m-%d)"
  2. echo "$my_date"

Remove Space From Variable:

  1. VAL='test string'
  2. echo "${VAL//\ /}"

Increment Variable:

  1. index=0
  2. index=$((index+1))

Substring

  1. VAL='test string'
  2. echo "${VAL:4:4}"

If value is equal to

  1. VAL='hello'
  2. if [ "$VAL" == 'hello' ] ; then
  3. echo 'Is Equal'
  4. fi

If with OR

  1. VAL='hello'
  2. if [ "$VAL" == 'hello' ] || [ "$VAL" != 'hi' ] ; then
  3. echo 'Is Hello'
  4. fi

If Variable is Empty

  1. VAL=''
  2. if [ -z "$VAL" ] ; then
  3. echo 'Is Empty'
  4. fi

Append to File

  1. echo 'Hi' >> file_to_log_to.log

Write to File

  1. echo 'Hi' > file_to_log_to.log

While Loop: Increment to 10

This will loop till the value is 9 then exit.

  1. i=0
  2. while [ $i -lt 10 ];
  3. do
  4. echo "$i"
  5. done

whoami

  1. USER=$(whoami)

If Variable Contains Text

  1. VAL='my Test String'
  2. if [[ "${VAL,,}" == *"test"* ]] ; then
  3. echo "Found test"
  4. fi

Color Coding

  1. NoColor=$'\033[0m'
  2. READ=$'\033[0;31m'
  3. GREEN=$'\033[0;32m'
  4. YELLOW=$'\033[1;33;40m'
  5.  
  6. printf "%s Variable Not Set %s\n" "${RED}" "${NoColor}"

Get Log to a logfile and console

  1. SOME_COMMAND 2>&1 | tee -a "${LOG_FILE_PATH}"

Read a JSON config

  1. JSON=$(cat "/path/to/json/file.json")
  2. export MY_VAR=$(echo "${JSON}" | python -c 'import json,sys;obj=json.load(sys.stdin);print(obj["MyKey"])')

Extract tar to Folder

  1. sudo tar -xvf /the/location/file.tar -C /to/location/ --force-local --no-same-owner

Update Certificates

This will update certificates. After you put a certificate in /usr/local/share/ca-certificates/

  1. update-ca-certificates

PipeStatus

  1. somecommand
  2. RETURN_CODE=${PIPESTATUS[0]}