Programming/Bash: Difference between revisions

From Dev Wiki
Jump to navigation Jump to search
(Update comments section)
(Correct variable section)
Line 20: Line 20:
  a_bool=true
  a_bool=true
  b_bool=false
  b_bool=false
  my_var="This is a string."
  my_var_1="This is "
my_var_2="a string."


=== Variable Usage ===
=== Variable Usage ===

Revision as of 18:02, 13 February 2020

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

Comments

Inline Comments

# This is an inline comment.

Block Level Comments

Block level comments don't truly exist in Bash.

However, there is a hackish way to implement them anyways, according to https://stackoverflow.com/a/43158193 { warn | It's recommended to use multiple inline comments instead, as this may not always work with all systems. }

: '
This is a block comment.
Comment line 2.
Another block comment line.
'

Variables

Variable Definition

a_bool=true
b_bool=false
my_var_1="This is "
my_var_2="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/*}