In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:

echo "$var"

This gives the expected value in all the examples given. Always quote variable references!


Why?

When a variable is unquoted, it will:

  1. Undergo field splitting where the value is split into multiple words on whitespace (by default):

    Before: /* Foobar is free software */

    After: /*, Foobar, is, free, software, */

  2. Each of these words will undergo pathname expansion, where patterns are expanded into matching files:

    Before: /*

    After: /bin, /boot, /dev, /etc, /home, ...

  3. Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving

    /bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
    

    instead of the variable's value.

When the variable is quoted it will:

  1. Be substituted for its value.
  2. There is no step 2.

This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.

Answer from that other guy on Stack Overflow
Top answer
1 of 7
222

In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:

echo "$var"

This gives the expected value in all the examples given. Always quote variable references!


Why?

When a variable is unquoted, it will:

  1. Undergo field splitting where the value is split into multiple words on whitespace (by default):

    Before: /* Foobar is free software */

    After: /*, Foobar, is, free, software, */

  2. Each of these words will undergo pathname expansion, where patterns are expanded into matching files:

    Before: /*

    After: /bin, /boot, /dev, /etc, /home, ...

  3. Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving

    /bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
    

    instead of the variable's value.

When the variable is quoted it will:

  1. Be substituted for its value.
  2. There is no step 2.

This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.

2 of 7
27

You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:

Why do I need to write "$foo"? What happens without the quotes?

$foo does not mean “take the value of the variable foo”. It means something much more complex:

  • First, take the value of the variable.
  • Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains foo * bar ​ then the result of this step is the 3-element list foo, *, bar.
  • Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing foo, following by the list of files in the current directory, and finally bar. If the current directory is empty, the result is foo, *, bar.

Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception: "$@" to expand to the list of positional parameters, e.g. "$@" is equivalent to "2" "$3" if there are three positional parameters. See What is the difference between @?)

The same happens to command substitution with $(foo) or with `foo`. On a side note, don't use `foo`: its quoting rules are weird and non-portable, and all modern shells support $(foo) which is absolutely equivalent except for having intuitive quoting rules.

The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming IFS doesn't contain digits or -).

See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.

Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.

People also ask

What does the echo command do in Linux?
The `echo` command prints its arguments to standard output. It is most commonly used in shell scripts to display messages, show the value of a variable, or write a line of text to a file. By default, `echo` also adds a newline at the end of the output.
🌐
linuxize.com
linuxize.com › home › bash › echo command in linux: print text and variables
echo Command in Linux: Print Text and Variables | Linuxize
What is the difference between `echo` and `printf`?
`echo` automatically adds a trailing newline and has limited formatting options. `printf` supports format specifiers (like `%s`, `%d`) and does not add a newline unless you include `\n`. Use `printf` when you need precise control over output formatting.
🌐
linuxize.com
linuxize.com › home › bash › echo command in linux: print text and variables
echo Command in Linux: Print Text and Variables | Linuxize
Why does `echo` behave differently on macOS?
`echo` options and escape handling are not fully portable across shells and systems. Use `printf` when you need consistent behavior across Linux, macOS, and other Unix-like systems.
🌐
linuxize.com
linuxize.com › home › bash › echo command in linux: print text and variables
echo Command in Linux: Print Text and Variables | Linuxize
🌐
W3Schools
w3schools.com › bash › bash_variables.php
Bash Variables
Arithmetic: Perform calculations using variables. # Concatenation greeting="Hello, " name="World" echo "$greeting$name" # Arithmetic num1=5 num2=10 sum=$((num1 + num2)) echo "The sum is $sum"
🌐
Reddit
reddit.com › r/bash › save result of echo command in a variable
r/bash on Reddit: Save result of echo command in a variable
November 17, 2022 -

This is a very basic question, but I am new to bash scripting. In the code snippet below, I am trying to extract something from a file and save it to a variable. What I have shown in the first echo command is working correctly. Instead of echoing it, I want to save it to a variable. The stuff below that is not working, I feel like maybe I am missing brackets or have the $ in the wrong place. Thanks in advance for your help! Sorry about the bad formatting, I am posting from my phone.

!/bin/bash

header_file="../../build.vivado/output/headers/axi_gp_header.vh"

Extract the 3rd word (reg value) from the line that contains the word "DIAGNOSTICS":

echo $(grep "DIAGNOSTICS" $header_file) | cut -d " " -f 3

This does not print the same thing as above:

REG_VALUE=$((grep "DIAGNOSTICS" $header_file) | cut -d " " -f 3) echo $REG_VALUE

🌐
Medium
medium.com › @asfnaiska › bash-echo-11ef473e05bf
[Bash] echo — Cookbook
November 16, 2024 - $ echo "this is my message in 2 file" | tee -a file1 file2 # -a is append. $ cat file1 this is my message in 2 file $ cat file2 this is my message in 2 file · You need to use -e because in variable RED & NC have escape character which is \033.
Find elsewhere
🌐
Linuxize
linuxize.com › home › bash › echo command in linux: print text and variables
echo Command in Linux: Print Text and Variables | Linuxize
May 9, 2026 - echo is a shell builtin in Bash and most other popular shells like Zsh and Ksh. There is also a standalone /usr/bin/echo utility, but the shell builtin version takes precedence. ... Hello, World! The command prints the text exactly as it was passed to echo and adds a newline at the end. Although not required, it is a good practice to enclose arguments in double or single quotes. When using single quotes '', the literal value of each character is preserved and variables are not expanded.
🌐
Baeldung
baeldung.com › home › scripting › how to echo the variable name instead of variable value
How to Echo the Variable Name Instead of Variable Value | Baeldung on Linux
August 26, 2023 - Here, we used the echo command to output the unquoted argument Linux we passed to it. In this case, the command sees that argument as a regular string. Let’s review how we can assign a value to variables: ... Here, varName is the variable name, and Linux is the variable value.
🌐
Baeldung
baeldung.com › home › files › file editing › how to write bash variable contents to a file
How to Write Bash Variable Contents to a File | Baeldung on Linux
March 25, 2025 - In this tutorial, we’ll present a few ways to write information stored in Bash variables to a file. One way we can write variable contents to a file is to use the echo command along with the redirect operator.
🌐
Jakami
wikipedia.jakami.de › content › askubuntu.com_en_all_2025-12 › questions › 1341726 › how-to-use-echo-output-as-a-variable
How to use echo output as a variable - Ask Ubuntu
May 31, 2021 - $ foo=hello $ bar=$(echo "\$foo") $ echo "$bar" $foo $ eval echo "$bar" hello $ foo=world $ eval echo "$bar" world · In the above example, the eval bash builtin command will parse the arguments once more, so that the $bar variable contents will be interpreted once more as a variable ($foo) and its current contents (hello in the first case and world in the second case) will be used as the argument to the echo command.
🌐
TestMu AI Community
community.testmuai.com › ask a question
How can I set a shell variable in a Bash script and access it later from the command line? - Ask a Question - TestMu AI Community
July 16, 2025 - I’m new to Bash scripting, and I’m trying to figure out how to create a script that stores the current directory path in a variable and lets me access that variable later in the terminal. Here’s what I’ve tried: #!/bin/bash mypath=$(pwd) cd $1 echo $mypath exec bash The script prints the path as expected, but when I go back to the command line and type echo $mypath, it’s empty.
🌐
Opensource.com
opensource.com › article › 19 › 8 › using-variables-bash
Using variables in Bash | Opensource.com
August 26, 2019 - If you would rather not override it, there’s a special syntax to set a variable to its existing value unless its existing value is empty. For this example, assume that FOO is set to /home/seth/Documents: $ FOO=${FOO:-"bar"} $ echo $FOO ...
🌐
W3Resource
w3resource.com › bash-script-exercises › variable-declaration-and-usage.php
Bash Variables: Declaration, usage and explanation
July 26, 2025 - Store the input in a variable named "mobile" and display a message including their favorite mobile. ... #!/bin/bash # Shebang line: Indicates the path to the shell interpreter (in this case, bash) # Prompting the user to enter their favorite mobile echo "Please input your favorite mobile:" # Reading user input and storing it in a variable named "mobile" read mobile # Printing a message including the user's favorite mobile echo "My favorite mobile is $mobile."
🌐
Flutter
docs.flutter.dev › install › add-to-path
Add Flutter to your PATH
$ echo 'export PATH="$HOME/develop/flutter/bin:$PATH"' >> ~/.bashrc content_copy
🌐
GeeksforGeeks
geeksforgeeks.org › linux-unix › bash-script-define-bash-variables-and-its-types
Bash Script - Define Bash Variables and its types - GeeksforGeeks
May 6, 2026 - The -i option of the declare command defines a variable as an integer type. Bash treats every value assigned to it as an arithmetic expression and automatically evaluates it as an integer. #!/bin/bash declare -i myvar myvar=5 myvar=myvar+10 echo $myvar
🌐
Northern Kentucky University
websites.nku.edu › ~foxr › CIT130 › tutorials › echo.html
Bash Echo Command
Here we look at how to use echo in Bash to output values stored in variables. If the variable's value contains a space, we have to place the entire right hand side of the assignment statement in quote marks.
🌐
CSE CGI Server
cgi.cse.unsw.edu.au › ~cs2041 › 26T1 › assignments › ass2 › index.html
COMP(2041|9044) 26T1 — Assignment 2: Sharpie
April 14, 2026 - Echo only accepts a single flag, -n, and it must be the first argument. -n at any other location, or any other flag, should be treated as a normal string. The $# variable is used to access the number of command-line arguments.
🌐
Hostinger
hostinger.com › home › tutorials › what are bash variables and how to use them effectively
How to use bash variables: Examples, types, and syntax
November 28, 2025 - For example, this script utilizes special variables to display its own name, process ID, and the success status of a command. #!/bin/bash echo "Script filename: $0" echo "Current Process ID: $$" # Attempt to list a non-existent file to generate an error ls /dummy_file 2>/dev/null # Print the exit code of the previous command echo "Exit status (0=Success, Non-zero=Fail): $?"
🌐
OpenAI Help Center
help.openai.com › en › articles › 5112595-best-practices-for-api-key-safety
Best Practices for API Key Safety | OpenAI Help Center
echo "export OPENAI_API_KEY='yourkey'" >> ~/.zshrc ... Confirm that you have set your environment variable using the following command. ... The value of your API key will be the resulting output. Option 2: Set your ‘OPENAI_API_KEY’ Environment Variable using bash Follow the directions in Option 1, replacing .zshrc with .bash_profile.