Day-10: So I did continued with bash scripting today! Going more deep in bash scripts! Check out my Bash Scripting - #1 before reading the below notes!
Variables!
- In bash syntax, variables $1 to represent the first command-line argument, $2 to represent the second command-line argument, and so on. And “$@” is the variable name for all arguments passed in. Use the syntax
VARIABLE_NAME=VARIABLE_VALUE
#!/bin/bash
BIRTHDATE=$1
Operating the Variables!
- The user’s input string will be in the format of “2020–05–06”, we can convert the user’s birthdate to a Unix timestamp.
#!/bin/bash
BIRTHDATE=$(date -jf “%Y-%m-%d” $1 +%s)
NOW=$(date -jf “%a %b %d %T %Z %Y” “$(date)” +%s)
DIFF_IN_SECONDS=$(expr $NOW — $BIRTHDATE)
DIFF_IN_DAYS=$(expr $DIFF_IN_SECONDS / 86400)
echo "You are $DIFF_IN_DAYS days old."
- Breaking down, The $() tells Unix to execute the command surrounded by the parenthesis and replace the variable with the output of the command. This is called "command substitution".
- Date: displays time on Unix systems!
-
-jf
: Convert one date format to another - '%Y-%m-%d': Tells date that the input date string will be in the format of year-month-day!
- $1: Specifies that the input string is the first argument of the script!
+%s: Tells date to output the date as the number of seconds that have passed since the “Unix epoch”.
The second line command:
NOW=$(date -jf “%a %b %d %T %Z %Y” “$(date)” +%s)
in this converted the current time into a Unix timestamp.The third line command:
DIFF_IN_SECONDS=$(expr $NOW — $BIRTHDATE)
in this calculated the difference between the two dates in seconds. We can calculate the difference between the two timestamps by using"expr"
.The fourth line command:
DIFF_IN_DAYS=$(expr $DIFF_IN_SECONDS / 86400)
then converted the difference in seconds to a difference in days by dividing the time difference in seconds by 86400. 86400 Seconds = 1 day.The fifth line command:
echo "You are $DIFF_IN_DAYS days old."
used echo then to display the time difference!
Resources:
Bash Scripting Cheatsheet: https://devhints.io/bash
Bash Script examples: https://linuxhint.com/30_bash_script_examples/
Medium Blog: Bash Scripting (You need Premium subs to access this!)
Contact:
Got doubts? Contact me on Twitter.
Feedbacks are welcomed, do comment it down below! :)
Top comments (0)