I’m quite new to programming. I’m trying to create a script which I’ll run on 3 servers. This script should get the hostname and then run the appropriate command. I guess I should have use ‘cases’ although I’m not sure how.
Here’s my code below.
#!/bin/bash
#Get hostname
hostname="$HOSTNAME"
PATH_DEV="some_path"
PATH_PREPROD="some_path"
PATH_PROD="some_path"
if [ $hostname == "dev" ];
then
find $PATH_DEV -name '*.mysql.gz' -type f -mtime +7 -exec rm -rf '{}' \;
elif [ $hostname == "prod" ];
then
find $PATH_PROD -name '*.mysql.gz' -type f -mtime +7 -exec rm -rf '{}' \;
elif [ $hostname == "preprod" ];
then
find $PATH_PREPROD -name '*.mysql.gz' -type f -mtime +7 -exec rm -rf '{}' \;
else
echo "Unknown hostname!";
fi
It’s only will run on “dev”. For the other 2 cases, it’ll return “Unknown hostname!”
What I’m doing wrong? 🙁
Thanks.
Well, your main question has already been kinda answered in the comments. But as you mentioned that you probably better use
case, here is the thing: Your assumption is correct, you definitely should use acasestatement instead of theif–elif-construct. One of the advantages will be that matching the host name against patterns will will also solve the problem of fully qualified host names for you. Here is my solution:The case statement evaluates the value in $HOSTNAME and checks if it is “dev” or starts with “dev.”, if it is “prod” or starts with “prod.”, if it is “devprod” or starts with “devprod.” respectively. When a match is made, the variable PATH_TO_USE is set to the value of the corresponding PATH_XXX variable. If no specific match is found, the match-always-pattern
*)will match and the script terminates with an error message (note that the error message contains the not-matching host name. This safes a lot of work sometimes 😉 ).If all goes well, the find command is executed at the end. (Another note: try to avoid duplication wherever you can. Doing one find command at the end allows you to change its other parameters in one place.).