Bash Shell: Trim Leading White Space From Input Variables

In Bash, you can use parameter expansion to trim leading white space from input variables. Here’s an example:

#!/bin/bash

input=" hello world"
trimmed=${input#"${input%%[![:space:]]*}"}
echo "Original input: \"$input\""
echo "Trimmed input: \"$trimmed\""

In this example, the input variable is assigned a value with leading white space. The trimmed variable uses parameter expansion to remove the leading white space. Here’s how the parameter expansion works:

  • ${input%%[![:space:]]*} expands to the longest leading substring of input that does not contain any non-white space characters. This effectively removes all leading white space from the input variable.
  • "${input%%[![:space:]]*}" is used to surround the expression and create a string with the trimmed value.
  • ${input#"${input%%[![:space:]]*}"} expands to the value of input with the trimmed value removed from the beginning. This effectively removes the leading white space from the input variable.

After running the script, the output should be:

Original input: " hello world"
Trimmed input: "hello world"

Note that this approach only trims leading white space from the input variable. If you also need to trim trailing white space or white space in the middle of the string, you can use similar parameter expansion techniques.

Leave a Comment