Variables
A variable is a name that stores a value, so you can use it later.
set name Obayecho "hi $name"# hi ObayIn fish you write set, then the name, then the value. To read it back, put a $ in front.
name=Obayecho "hi $name"# hi ObayIn bash you write name=value with no spaces around the =. name = Obay won’t work, because bash thinks you’re running a command called name.
A variable can also hold several values.
set colors red green blueecho $colors[2]# greencount $colors# 3In fish, every variable is a list. A normal variable is just a list with one thing in it. Counting starts at 1.
colors=(red green blue)echo "${colors[1]}"# greenecho "${#colors[@]}"# 3Bash calls these arrays. Counting starts at 0, and the syntax is a bit longer. You’ll mostly see arrays in bigger scripts.
Environment variables
Section titled “Environment variables”Your shell starts with some variables already set. These are called environment variables, and they’re usually written in capital letters:
echo $HOME # your home folderecho $USER # your usernameecho $PATH # where the shell looks for commands$PATH is the list of folders where the shell looks for programs. When you type ls, the shell goes through those folders one by one until it finds a program called ls. You’ll use this in later chapters.
To make a variable visible to the programs you run, add -x (for export):
set -x EDITOR nanoThat lasts until you close the terminal. To keep it after that, add -U (for universal) as well:
set -Ux EDITOR nanoTo make a variable visible to the programs you run, use export:
export EDITOR=nanoThat lasts until you close the terminal. To keep it, put the same line in the file ~/.bashrc, which bash runs every time it starts.
Since variables are text, you need a command to do math:
math 2 + 3# 5math 10 / 4# 2.5echo $(( 2 + 3 ))# 5echo $(( 10 / 4 ))# 2Bash does math inside $(( )), and only with whole numbers, so 10 / 4 is 2.