Bash function example and trics

Validata correct number of arguments if [ "$#" -ne 2 ]; then echo "Illegal number of parameters ($#, should be 2)" exit 1 fi $# returns number of parameters passed to script. If it’s less then 2, script ends with error. Check if environment variable is set if [ -z "$CLEANING_JOB" ] then echo "Environmental variable [CLEANING_JOB] does not exist." exit 1 fi Bash function example set_dir_structure() { YEAR=$(date +"%Y" "$@") MONTH=$(date +"%m" "$@") DAY=$(date +"%d" "$@") HOUR=$(date +"%H" "$@") retval="$YEAR/$MONTH/$DAY/$HOUR" } This function can be executed with or without parameter to get proper dir structure related with date and time....

October 19, 2023 · 1 min

Change files extensions

Simple example of bash script that is changing files extension in desired directory: #!/bin/bash CURRENT_EXTENSION="${1-mp3}" NEW_EXTENSION="${2-mp4}" FILES_PATH="${3-$PWD}" FILES_LIST=$(find ${FILES_PATH} -maxdepth 1 -name "*.${CURRENT_EXTENSION}") for FILE in $FILES_LIST; do NEW_FILE=$(echo "$FILE" | sed "s/${CURRENT_EXTENSION}/${NEW_EXTENSION}/") echo "Renaming file: $FILE -> $NEW_FILE" mv $FILE $NEW_FILE done Usage You can use it by simple executing file: ./change_ext.sh It will be executed with default settings: extensions to change: mp3, new extension will be mp4 and script will look for files in current directory....

June 19, 2023 · 1 min