cut
Get clustername from hostname with cut and set it as an environment variable
This uses echo to send the hostname string to the cut command, which then splits the string by the hyphen (-d’-’) and returns the first field (-f1).
#!/bin/bash
# 1. Get the full hostname
FULL_HOSTNAME="blaat-c-1234"
echo "Original hostname: $FULL_HOSTNAME"
# 2. Pipe the hostname to 'cut' and capture the output
CLUSTER_PREFIX=$(echo "$FULL_HOSTNAME" | cut -d'-' -f1)
# 3. Verify the result
echo "Extracted prefix: $CLUSTER_PREFIX"
# 4. Export it as an environment variable
export CLUSTER_PREFIX
echo "The environment variable CLUSTER_PREFIX is now set to: $CLUSTER_PREFIX"
Using Bash Parameter Expansion
This method is the most efficient and recommended because it doesn’t require starting a new process (like cut or sed). It’s handled directly by the shell.
The syntax ${variable%%-*}
tells bash to take the variable and remove the longest matching part from the end (%%)
that follows the pattern -*
(a hyphen followed by anything).
This effectively cuts off everything from the first hyphen onwards.
#!/bin/bash
# 1. Get the full hostname (for this example, we'll assign it manually)
FULL_HOSTNAME="blaat-c-1234"
echo "Original hostname: $FULL_HOSTNAME"
# 2. Extract the prefix and assign it to a new variable
# The %%-* removes everything from the first '-' to the end.
CLUSTER_PREFIX="${FULL_HOSTNAME%%-*}"
# 3. Verify the result
echo "Extracted prefix: $CLUSTER_PREFIX"
# 4. Export it to make it an environment variable for child processes
export CLUSTER_PREFIX
# You can now use the variable elsewhere in your script
echo "The environment variable CLUSTER_PREFIX is now set to: $CLUSTER_PREFIX"
Using cut to extract the cluster name from the hostname
cut -d'-' -f2 <<< "$(hostname)"