§2023-09-09
In Bash, you can assign values to variables in several ways:
Direct Assignment: You can assign a value directly to a variable using the = operator. For example:
my_var="Hello, World!"
Command Substitution: You can assign the output of a command to a variable using command substitution, as shown in your original example:
my_var=$(command)
Using read: You can use the read command to read input from the user or from a file and assign it to a variable. For example:
read my_var
Array Assignment: In Bash, you can also work with arrays. You can assign values to an array using parentheses:
$ my_array=("apple" "banana" "cherry")
$ my_array=("apple" "banana" "cherry")
$ echo "${my_array[2]}"
cherry
$ echo "${my_array[0]}"
apple
alexlai@Surfa
MY_ENV_VAR="This is an environment variable"
my_var="$MY_ENV_VAR"
$ my_var="${MY_DEFAULT_VAR:-Default Value}"
$ echo $my_var
Default Value
$ my_var+=" more text"
$ echo $my_var
Default Value more text
$ num1=5
$ num2=3
$ result=$((num1 + num2))
$ echo $result
8
Return to Top