Programming/Bash

From Dev Wiki
< Programming
Revision as of 14:24, 13 February 2020 by Brodriguez (talk | contribs) (Create string manipulation section)
Jump to navigation Jump to search

Bash is primarily a Linux scripting language, but it works on all versions of Windows as well, if used through git.

Comments

# This is an inline comment

Variables

Variable Definition

a_bool=true
b_bool=false
my_var="This is a string."

Variable Usage

echo "Printing variable values."
echo $a_bool
echo $b_bool
echo ${my_var_1}${my_var_2}

If Statements

Basic If

if [[ $x == $y ]]
then
    # Logic if true.
fi

Full If

if [[ $x == $y ]]
then
    # Logic for "if" true.
elif [[ $x && ($y || $z) ]]
then
    # Logic for "else if" true.
else
    # Logic for false.
fi

String Manipulation

See https://stackoverflow.com/a/14703709

With bash, it's possible to dynamically trim strings, based on regex matches.
The syntax is:

# Trim shortest match from beginning.
${<string_value>#<regex>}

# Trim longest match from beginning.
${<string_value>##<regex>}

# Trim shortest match from end.
${<string_value>%<regex>}

# Trim longest match from end.
${<string_value>%%<regex>}


For example, if you have a string of

file_name="/home/user/my_dir/my_dir/my_file.tar.gz"

Then you can do the following manipulations:

# Get the full file extension.
# Outputs "tar.gz"
${file_name#*.}

# Get the last part of the file extension.
# Outputs "gz"
${file_name##*.}

# Get the full file name, including file extension.
# Outputs "my_file.tar.gz"
echo "b: ${file_name##*/}

# Get parent of current directory.
# Outputs "/home/user/my_dir/"
${file_name%my_dir/*}

# Get grandparent of current directory.
# Outputs "/home/user/"
${file_name%%my_dir/*}