Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Bash, command to variable (cat), output is on 1 line, <pre> is not working

In bash, output is on 1 line from command, so <pre> is not working in html tag.

How can I do get output to variable as classic line by line, not in one line?

Output (1 line).

But this command shows me this (with 2 lines).

genderbee's user avatar

  • What is the usage of the first line? Can you put the output of echo "$log" after the 1st line is executed in your question. –  FedKad Sep 30, 2019 at 9:00
  • You question is not clear. But, I think you need double quotes around $log like this: ...<pre>'"$log"'</pre> –  FedKad Sep 30, 2019 at 9:16

3 Answers 3

When a Bash variable contains multiple lines and you want to output it with echo as it is; you need to put double quotes ( " ) around the variable. For example:

If you put double quotes, the echo command will consider it as a single (whose contents happen to contain a multi-line string) parameter. If you don't put double quotes the contents of the string will be split (by Bash) into multiple parameters whenever a white-space (space, tab, newline, etc.) occurs.

For example:

Note, the first echo will get three parameters ( 'a' , 'b' , and 'c' ) and will output them by separating with a single space. The second echo will get a single parameter ( 'a b c' ) and will output it as it is.

FedKad's user avatar

  • Yes! You are right. What is difference if I don't use " ? Thanks. –  genderbee Sep 30, 2019 at 9:21

Your pre-tag is working fine. Your problem is that $log contains the output of cat on one line. Instead of trying to fix this, I would suggest you split this code into simpler steps.

First of all, this line:

Is way to complicated because it nests two command substitutions with two different syntaxes. You might understand it today, but why not split this into two steps so you or one of your co-workers will understand it a year from now:

Or even better (assuming the logfiles end in .log):

Now you see that you just put the contents of $logile into $logtext. You seem to want to output the content of $logfile between the pre-tags, just like it appears in the file. With the simplified commands above, it may appear obvious that putting it into $logtext is an extra step that isn't even needed. Just cat the file where you want it to appear. The backticks or the $()-construct is meant to feed one command with arguments that are created from the output of another. In this case that just messes it all up.

So what you could do is this:

or simply run the commands between brackets () to start a subshell with one redirect statement instead:

Oscar's user avatar

  • Ok, maybe it is better to have it separately. But what is difference between ' command ' and $(command) and when it is better use one method and when second method. Thanks. –  genderbee Sep 30, 2019 at 11:50
  • @genderbee, there is no difference, except you can't nest these backticks. However you ou could easily do echo $(echo $(echo $(echo Bazinga\!))) if you enjoy spawning three subshells just for fun. –  Oscar Sep 30, 2019 at 12:12
  • Bazinga......! :) –  genderbee Sep 30, 2019 at 12:14
  • @genderbee, as for the second part of your question: it depends on how you define "better". Often "easier to understand for the human reading it" counts as better than "clever demonstration of all your knowledge packed into one complex statement" –  Oscar Sep 30, 2019 at 12:15

special-purpose code block ( here doc ).

Using += operator to append to variable., you must log in to answer this question., not the answer you're looking for browse other questions tagged bash cat ..

  • The Overflow Blog
  • How to scale a business-ready AI platform with watsonx: Q&A with IBM sponsored post
  • Will developers return to hostile offices?
  • Featured on Meta
  • We're rolling back the changes to the Acceptable Use Policy (AUP)
  • Seeking feedback on tag colors update
  • Notifying users about the policy on AU concerning AI-generated content

Hot Network Questions

  • What's the circuitry inside triac driver optocouplers?
  • Jury and Witness intimidation
  • How to render an image the exact way its displayed in the vrendered preview
  • When are the chirp signals orthogonal?
  • Boiler *might* have caused water intrusion... who do I call?
  • Did Netanyahu say (apparently in 2001) "I actually stopped the Oslo Accords"?
  • My visit visa was cancelled at the border - am I banned?
  • A number sequence in disguise
  • How can I remove smoke from a bag of holding?
  • Yield of construction gingerbread
  • What would the effects of a space based laser weapon system capable of tracking and destroying any projectile posing a threat to human life?
  • Can we solve the environment with only the linear and angular position through Q-Learning?
  • Special topics for introductory probability
  • PSE Advent Calendar 2023 (Day 3): 24 dangerous doors
  • Is there an easily accessible way to make a surface very bright white?
  • Resolving an apparent contradiction between Schwarzschild and ingoing Eddington-Finkelstein coordinates
  • How does one get past unlucky work history streak?
  • Can federal courts overturn state court decisions on matters of state law?
  • Why are there so many pro-Palestinian protestors in the United States?
  • Distribute the code as closed source and the end users download GPLv3 dependencies separately
  • Why isn't the "Dark Matter" in the Bullet Cluster supermassive black holes?
  • Ice is melted in the water
  • I don't get why do we say that electric potential energy is stored in the electric field?
  • Advisor-student collaboration (or lack thereof) and paper authorship in mathematics: how does it work?

bash assign cat output to variable

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Shell Programming and Scripting

Redirect cat to variable.

Member Information Avatar

10 More Discussions You Might Find Interesting

1. shell programming and scripting, bash - trying to cat a file that is a variable, discussion started by: paperbackwriter, 2. unix for beginners questions & answers, carriage return with cat variable, discussion started by: arnaudh78, 3. shell programming and scripting, cat files listed in text file and redirect to new directory with same filename, discussion started by: trigger467, 4. unix for dummies questions & answers, how to append a string by cat and redirect to other file, discussion started by: stew, 5. shell programming and scripting, moving cat values to a variable, discussion started by: rajiv_kool, 6. shell programming and scripting, cat file with variable substitution, discussion started by: phil27577, 7. shell programming and scripting, cat redirect eof missing text, discussion started by: juanb25, 8. shell programming and scripting, cat > variable + format, discussion started by: josegr, 9. unix for dummies questions & answers, using a variable inside a file to cat another., discussion started by: maestrorage, 10. unix for dummies questions & answers, redirect to variable, discussion started by: mrad, member badges and information modal.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

cat command with a variable that has spaces

I need to use cat command to display the contents of a file, and the filename has spaces in them: "embedded board link.rtf".

I assign the filename using a variable: I="embedded board link.rtf" , but when I use cat $I , I have this error message.

What might be wrong?

  • command-line

prosseek's user avatar

You have to quote the variable too:

This is because the shell will first expand any variables, and then parse the command:

  • cat embedded board link.rtf

When you really meant the following:

  • cat "embedded board link.rtf"

Note that in bash and many other shells, variables inside single quotes will not be expanded:

Attie's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged linux command-line bash cat ..

  • The Overflow Blog
  • How to scale a business-ready AI platform with watsonx: Q&A with IBM sponsored post
  • Will developers return to hostile offices?
  • Featured on Meta
  • We're rolling back the changes to the Acceptable Use Policy (AUP)
  • Seeking feedback on tag colors update

Hot Network Questions

  • Can sine converge to zero at infinity?
  • What are the procedures in the United States for important people staying in the same place?
  • Tree in slide with pause for each node
  • Could an hypothetical hidden black hole companion to the sun be revealed by proper motion data?
  • Exponential operator approximation: Suzuki-Trotter Expansion
  • Jury and Witness intimidation
  • What does "everything" mean?
  • How can I remove smoke from a bag of holding?
  • If I cut out a square of drywall for access, should I tape the seams when I put it back?
  • What's the circuitry inside triac driver optocouplers?
  • Which LEGO set is a gray vehicle frame from?
  • Wavelength of "complementary colours"?
  • How do I typeset RTL language phrases inside a document with mostly LTR text?
  • Distribute the code as closed source and the end users download GPLv3 dependencies separately
  • Ice is melted in the water
  • How to handle URLs with TeX-special charactors in a footnote
  • "Make Our Life ..." vs "Make Our Lives ..."
  • How to apply the same formula to a whole column?
  • Advisor-student collaboration (or lack thereof) and paper authorship in mathematics: how does it work?
  • Is there a way to set macOS' accent color on a per-app basis?
  • Lack of mens rea defence to robbery
  • videos from non-linux partition don't play
  • Is it possible to record a Mac's screen while booting or during the initial set-up?
  • TikZ: Use \enquote in text along a path

bash assign cat output to variable

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

[Solved]-Bash Script store cat output in variable and then echo it-bash

variable assignments in bash should not have any spaces before or after the equal sign. it should be like this:

which can be written more idiomatically as

bash assign cat output to variable

Related Query

  • Bash Script store cat output in variable and then echo it
  • Bash script store command output into variable
  • bash script use cut command at variable and store result at another variable
  • Bash Script - store find command output without spaces in variable
  • How to store ImageMagick output into Bash variable (and then use it)?
  • bash script - use and expand variable in cat
  • How to store output from a remote host in a variable bash script
  • How to run a SQL command within a Bash script and save the output of that command to a variable
  • redirecting echo or printf output to variable which represents an std* stream in a bash script
  • Timeout a command efficiently and capture output to a variable in bash script
  • How to get cat output path as a variable in bash script
  • Writing a simple backup script in bash and sending echo output to email
  • How do I pass a variable (string) to a bash script from python and later echo it?
  • echo stderr and stdout to file from bash script variable
  • bash shell script - getting a string from the console and store it into a variable
  • Bash script : Storing command with spaces and arguments in variable and then executing
  • Can I set a bash script variable to the output of a command and to all lowercase purely with bash parameter expansion?
  • Linux bash shell script prompt user input and store in variable
  • Extract Random Filename Substring to Variable Output in Bash Script for FTP push and archive script
  • Bash script to read a text file and then output each line into variables
  • bash : parse output of command and store into variable
  • how to use for loop inside a echo statement in bash shell script and output to file
  • Store output of command in variable where the command is already executed/stored in it's own variable - bash script
  • How to assign a string column to variable and have it quoted in output in Bash script
  • Open editor from bash script and cat file to variable not working
  • Grab value of tail of file in bash script and store as variable
  • Use bash script to store output of git commands and send it in email
  • Finding the full path of a directory if it exists and store in a variable using bash script
  • shell script - store output of "kill -HUP 1234" (gunicorn command) to variable and check if the variable contains "No such process"
  • Bash script to output files NOT being currently used, then use result as a variable

More Query from same tag

  • Bash Scripting, Respond to Keypress
  • Checkin if a Variable File is in another directory
  • Unable to trap ctrl-c to exit function exit bash script
  • How do I make the scroll wheel work in an interactive tmux session with iterm2?
  • bash allow only positive integer or positive integer with decimal point
  • Listing non-admin accounts in OS X with dscl
  • bash 'while read line' efficiency with big file
  • find command argument -iname doesn't work from variable
  • trapping signal from "docker stop" in bash
  • I need to compare two lines in BASh script, ignoring whitespaces at the beginning and end, ignoring EOL / EOF
  • How to get a stdout message once a background process finishes?
  • How can I memory-efficiently iterate over a huge range of numbers in bash?
  • ZSH/BASH per directory history
  • How to combine the content of two files by matching the data
  • Using a BASH script to edit a Mongo database when there is no Mongo client installed
  • Get the Pid of the background process executed using bash -c
  • Write the file name before deleting
  • How to access global environment through groovy script in Jenkins Pipeline Plugin
  • How to turn content between two lines into single line?
  • Using bash comm command on columns but returning the entire line
  • variable does not print in a function as expected
  • How to replace between symbols with sed command in bash
  • Jenkins build output set as current build description
  • Formatting email body in s-nail command bash
  • How can I make a bash script case insensitive?
  • sed replace hash with another hash in a file
  • Search with grep for two expressions at once
  • Shell script to wait for the prompt and pass user input
  • redirect the sql query will add all the files in that directory
  • in bash when i try to check for null or empty using if statement get syntax error

Copyright 2023 www.appsloveworld.com . All rights reserved.

Bash variables and command substitution

Using variables to refer to data, including the results of a command.

An essential feature of programming is the ability to use a name or a label to refer to some other quantity: such as a value, or a command. This is commonly referred to as variables .

Variables can be used, at the very least, to make code more readable for humans:

However, variables really come into use in more advanced programming, when we're in a situation in which the actual values aren't known before executing a program. A variable acts as a placeholder that gets resolved upon actual execution time.

For example, imagine that websites.txt contains a list of website addresses. The following routine reads each line (via cat , which isn't best practice…but will do for now) into a for loop, which then downloads each URL:

Basic variable usage and syntax

Setting a variable.

The following command assigns Hello World to the variable named var_a , and 42 to another_var

Unlike most modern languages, Bash is pretty picky about the syntax for setting variables. In particular, no whitespace is allowed between the variable name, the equals sign, and the value.

All of these examples would cause Bash to throw an error:

Referencing the value of a variable

Whenever Bash encounters a dollar-sign , immediately followed by a word, within a command or in a double-quoted string, it will attempt to replace that token with the value of the named variable. This is sometimes referred to as expanding the variable , or parameter substitution :

Failure to dereference

When a dollar-sign doesn't precede a variable name, or a variable reference is within single-quotes , Bash will interpret the string literally :

Concatenating strings

Variables can be very useful for text-patterns that will be repeatedly used:

If your variable name butts up against a literal alphanumeric character, you can use this more verbose form, involving curly braces , to reference a variable's value:

Valid variable names

Variable names can contain a sequence of alphanumeric characters and underscores. For variables created by you, the user, they should start with either an alphabetical letter or an underscore (i.e. not a number):

Valid variable names:

  • GRATUITOUSLY_LONG_NAME

When we write functions and shell scripts, in which arguments are passed in to be processed, the arguments will be passed int numerically-named variables, e.g. $1 , $2 , $3

For example:

Inside my_script.sh , commands will use $1 to refer to Hello , $2 to 42 , and $3 for World

The variable reference, $0 , will expand to the current script's name, e.g. my_script.sh

Command substitution

The standard output of a command can be encapsulated, much like a value can be stored in a value, and then expanded by the shell.

This is known as command substitution . From the Bash documentation :

Command substitution allows the output of a command to replace the command itself. Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

As an example, consider the seq command, which will print a sequence of numbers starting from the first argument to the second argument:

With command substitution, we can encapsulate the result of seq 1 5 into a variable by enclosing the command with $( and ) , and pass it as an argument to another command:

Variables and command expansion

When a command is replaced by its standard output, that output, presumably just text, can be assigned to a variable like any other value:

The loss of newlines in command substitution

Earlier, I quoted from the Bash documentation on command expansion. Here's an emphasized version of the excerpt:

What does that mean? Consider seq 1 5 being called normally, and then, via command substitution, and note the change in formatting:

Why do the newlines get removed during the command expansion? It's something we'll encounter later (and there's a section on it at the end of this tutorial) and deals with how Bash interprets space and newline characters during expansion. Anyway, it's worth noting the behavior for now, as it may be new to you if you're coming from another programming language.

Arithmetic expansion

To do basic calculations, you can enclose an expression inside $(( )) :

Check the Bash documentation for the full set of arithmetic operators . Math at the command-line can be a bit clunky so we won't be focusing too much on it.

The bc utility

An aside: if you want to do more advanced math from the command line, use bc , which reads in from stdout and evaluates the expression:

Word-splitting in the wild

This section covers more technical details of how Bash handles space characters when it does an exapansion. It's not necessary to memorize for the specific assignments in this class. However, as many of you are wont to copy and paste code directly from things you've seen on the Internet, it might be worth knowing all the different ways you could accidentally harm yourself, due to the way Bash handles spaces and newline characters.

Here's the Bash documentation for the concept known as "word-splitting"

The internal field separator

The global variable IFS is what Bash uses to split a string of expanded into separate words …think of it as how Excel knows to split a CSV (comma-separated-values) text file into a spreadsheet: it assumes the commas separate the columns.

Let's pretend that IFS has been set to something arbitrary, like a capital Z . When Bash expands a variable that happens to contain a Z , the value of that variable will be split into separate words (and the literal Z will disappear):

By default, the IFS variable is set to three characters: newline , space , and the tab . If you echo $IFS , you won't see anything because those characters…well, how do you see a space character if there aren't any visible characters?

The upshot is that you may see code snippets online in which the IFS variable is changed to something like $'\n' (which stands for the newline character).

Imagine a textfile that contains a bunch of lines of text that, for example, may refer to filenames:

When Bash reads each line of the file, the default value of IFS , which includes a space character , will cause Bash to treat the file named rough draft.txt as two files, rough and draft.txt , because the space character is used to split words.

With IFS set to just the newline character, rough draft.txt is treated as a single filename.

This concept will make sense when it comes to reading text files and operating on each line. I don't expect you to fully understand this, but only to be aware of it, just in case you are haphazardly copy-pasting code from the Internet.

The dangers of unquoted variables

In an ideal world, everyone would keep their string values short and without space/newline, or any other special characters. In that ideal world, the following unquoted variable reference would work just fine:

But when people start adding special characters to filenames, such as spaces, expanding variables, without the use of double quotes , can be dangerous .

In the following example, the programmer intends the file named Junk Final.docx to be deleted:

Unexpected word-splitting

However, when referenced without double-quotes , Bash sees file_to_kill as containing two separate values, Junk and Final.docx . The subsequent rm command will attempt to delete those two files , and not Junk Final.docx :

Unexpected special characters in filenames

Ah, no harm done , you say, because those files didn't exist in the first place. OK, but what happens when someone puts a star (i.e. asterisk ) into a filename? You're aware of what happens when you do grep * and rm * – the star acts as a wildcard, grabbing every file.

So you'll see the previous errors, since Junk and Final.docx don't exist. But in between those attempted deletions, rm will run on * …so say bye-bye to every file in that directory.

Here's the animated GIF version:

Notice how rm "$filename" affects only the file that is named, * LOL BYE FILES .

So the main takeaway here is: double-quote your variable references whenever possible .

To reiterate

Expanding a variable can lead to unexpected and sometimes catastrophic results if the variable contains special characters:

Expanding a variable within double-quotes can prevent such problems:

Who would do such a thing?

You might think, Who the hell puts star characters in their filenames? Well, besides people who really enjoy star-shaped symbols, malicious hackers and pranksters. And variables usually aren't just manually assigned by the result of human typing. As you've read above, sometimes the result of commands are stored in a variable. And if such commands are processing raw data, it's not unimaginable that the raw data, quite innocently, contains special characters that are destructive to certain Bash programs.

For the purposes of the CompCiv course, the assignments will try to stay far from untrusted sources of data. But keep in mind the dangers of just pasting in seemingly safe-looking code. Bash's syntax and behavior in handling strings is hard to fully comprehend, which is why developers use other languages for more complex applications.

You can read more about quoting variables . There's a lot of minutiae, but the main takeaway, besides general safety , is to have a general understanding how Bash, and any other programming environment, uses certain conventions and syntax rules to deal with the myriad ways that users want to pass around values in their programs.

IMAGES

  1. [Solved] How to assign the cat output of a bash script to

    bash assign cat output to variable

  2. Bash Variables

    bash assign cat output to variable

  3. Unix & Linux: How to assign the cat output of a bash script to a variable in another script

    bash assign cat output to variable

  4. Bash Assign Default Value if Variable Unset

    bash assign cat output to variable

  5. How to Use the “cat” Command in Bash?

    bash assign cat output to variable

  6. Bash Function & How to Use It {Variables, Arguments, Return}

    bash assign cat output to variable

VIDEO

  1. DataSet and Data Adapter in C#

  2. Cat® 966K XE Wheel Loader in Action

  3. Cat , Wadadadadang #groovesoulsongs

  4. assign variable in c program #cprogramming #coding #cprogrammingvideo #tutorial

  5. Cat® Flexible Camshaft Technology Save Fuel & Lowers Emissions

  6. Cat bash boombastic!! #funny

COMMENTS

  1. What Is a Qualitative Variable?

    Qualitative variables are those with no natural or logical order. While scientists often assign a number to each, these numbers are not meaningful in any way. Examples of qualitative variables include things such as color, shape or pattern.

  2. What Does Input and Output Mean in Math?

    Mathematical equations called functions use input and output replace the variables in an equation. The input is the known variable, while the output is the solution. Use functions any time a variable (x) transforms in a relationship to equa...

  3. What Is a Fixed Resource and a Variable Resource?

    A fixed resource remains unchanged as output increases, and a variable resource changes in tandem with output. All resources are utilized as inputs in the production process. The four factors of production are land, labor, capital and entre...

  4. How to assign the cat output of a bash script to a variable in another

    How to assign the cat output of a bash script to a variable in another script · shell-script · cat · variable.

  5. Bash Script store cat output in variable and then echo it [duplicate]

    Variable assignments in bash should not have any spaces before or after the equal sign. It should be like this: #!/bin/bash var=$(cat

  6. Bash, command to variable (cat), output is on 1 line, <pre> is not

    When a Bash variable contains multiple lines and you want to output it with echo as it is; you need to put double quotes ( " ) around the

  7. Bash Assign Output of Shell Command To Variable

    This quick tutorial explains how to assign the output of a bash shell command to a variable under a Linux, macOS, *BSD, or Unix systems.

  8. redirect cat to variable

    syntax below and content of output file below. cat > S99build << EOF > #!/bin/bash > case $1 in > 'start') > /usr/os-buildsol.sh > >

  9. cat command with a variable that has spaces

    I assign the filename using a variable: I="embedded board link.rtf ... How are bash variables containing a file path with non-ascii

  10. [Solved]-Bash Script store cat output in variable and then echo it-bash

    variable assignments in bash should not have any spaces before or after the equal sign. it should be like this: #!/bin/bash var=$(cat tmp/pids/unicorn.pid)

  11. BASH command output to the variable

    Run the script. $ cat weekday.txt $ bash cmdsub1.sh. Output: Using command substitution in loop. You can store the output of command substitution into any

  12. How to Assign the Output of a Command Like tee to a Variable

    ... output of tee in a variable instead of a file. We tested the code in this tutorial on Debian 11 (Bullseye) with GNU Bash 5.1.4. It should

  13. Preserve Linebreaks When Storing Command Output to a Variable

    txt file contains three lines. Now, let's assign the output of the cat command above to a shell variable using command substitution: VAR=$(cat

  14. Bash variables and command substitution

    When a command is replaced by its standard output, that output, presumably