Bash Script Knowledge Base
This article holds some notes about scriping in bash.
Siehe auch: Shell-Skript How-To (Linux)
General
A bash script starts in the first line with:
#!/bin/bash
Variables
Define variable MY_STR:
HW="Hello World!"
Read content of the variable and put it to the console:
echo $HW
Source: https://www.geeksforgeeks.org/bash-script-working-of-bash-variables/
Working with Dates
To extract year, month or day (among others) from the system date :
date '+%Y-%m-%d'
Hint: The plus sign is needed for a reason I cannot explain.
The previous output always refers to the present, which at the time of writing this was:
2025-09-29
To have it work on a different reference date use:
date -d '2025-12-24' '+%m/%d/%Y'
For further variables see https://man7.org/linux/man-pages/man1/date.1.html
Output:
12/24/2025
Save the output in a variable in a bash script and print it out and also print it out directly:
#!/bin/bash
MONTH=$(date '+%Y-%m')
echo "***$MONTH***"
echo "***$(date '+%m/%d/%Y')***"
Output as of the time of writing:
***2025-09*** ***09/29/2025***
Check if Bash Script Received Parameters
Check if any arguments were passed to the script:
if [ $# -eq 0 ]; then echo "No arguments received" else echo "Arguments received" fi
$# contains how many arguments were passed to the script.
Check if first argument was empty:
if [ -z "$1" ]; then echo "Argument 1 empty" else echo "Argument 1 is $1" fi
The -z switch will test, if the argument passed is empty. If it is empty, then the expression resolves to true and the body of the if statement is executed.
Sources:
https://stackoverflow.com/questions/6482377/check-existence-of-input-argument-in-a-bash-shell-script
