How do I read a variable from a file?












55















I want to insert in my script a value (string) that I would read from a text file.



For example, instead of:



echo "Enter your name"
read name


I want to read a string from another text file so the interpreter should read the string from the file and not the user input.










share|improve this question




















  • 1





    What does your text file look like? Is the entire file 1 variable or are they KEY=VALUE pairs? The solutions are quite different (if it's the latter, Takkat's answer applies, the former Radu's)

    – kiri
    Oct 28 '13 at 11:37






  • 1





    @CiroSantilli it is not crossposted if it was posted by a different user, there is no such thing as a "cross-site duplicate". The only thing that should be avoided is the same question asked by the same user on different sites.

    – terdon
    Mar 24 '14 at 17:52
















55















I want to insert in my script a value (string) that I would read from a text file.



For example, instead of:



echo "Enter your name"
read name


I want to read a string from another text file so the interpreter should read the string from the file and not the user input.










share|improve this question




















  • 1





    What does your text file look like? Is the entire file 1 variable or are they KEY=VALUE pairs? The solutions are quite different (if it's the latter, Takkat's answer applies, the former Radu's)

    – kiri
    Oct 28 '13 at 11:37






  • 1





    @CiroSantilli it is not crossposted if it was posted by a different user, there is no such thing as a "cross-site duplicate". The only thing that should be avoided is the same question asked by the same user on different sites.

    – terdon
    Mar 24 '14 at 17:52














55












55








55


13






I want to insert in my script a value (string) that I would read from a text file.



For example, instead of:



echo "Enter your name"
read name


I want to read a string from another text file so the interpreter should read the string from the file and not the user input.










share|improve this question
















I want to insert in my script a value (string) that I would read from a text file.



For example, instead of:



echo "Enter your name"
read name


I want to read a string from another text file so the interpreter should read the string from the file and not the user input.







bash scripts






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 28 '13 at 10:03









Braiam

52.2k20136222




52.2k20136222










asked Oct 28 '13 at 8:35









user208413user208413

291133




291133








  • 1





    What does your text file look like? Is the entire file 1 variable or are they KEY=VALUE pairs? The solutions are quite different (if it's the latter, Takkat's answer applies, the former Radu's)

    – kiri
    Oct 28 '13 at 11:37






  • 1





    @CiroSantilli it is not crossposted if it was posted by a different user, there is no such thing as a "cross-site duplicate". The only thing that should be avoided is the same question asked by the same user on different sites.

    – terdon
    Mar 24 '14 at 17:52














  • 1





    What does your text file look like? Is the entire file 1 variable or are they KEY=VALUE pairs? The solutions are quite different (if it's the latter, Takkat's answer applies, the former Radu's)

    – kiri
    Oct 28 '13 at 11:37






  • 1





    @CiroSantilli it is not crossposted if it was posted by a different user, there is no such thing as a "cross-site duplicate". The only thing that should be avoided is the same question asked by the same user on different sites.

    – terdon
    Mar 24 '14 at 17:52








1




1





What does your text file look like? Is the entire file 1 variable or are they KEY=VALUE pairs? The solutions are quite different (if it's the latter, Takkat's answer applies, the former Radu's)

– kiri
Oct 28 '13 at 11:37





What does your text file look like? Is the entire file 1 variable or are they KEY=VALUE pairs? The solutions are quite different (if it's the latter, Takkat's answer applies, the former Radu's)

– kiri
Oct 28 '13 at 11:37




1




1





@CiroSantilli it is not crossposted if it was posted by a different user, there is no such thing as a "cross-site duplicate". The only thing that should be avoided is the same question asked by the same user on different sites.

– terdon
Mar 24 '14 at 17:52





@CiroSantilli it is not crossposted if it was posted by a different user, there is no such thing as a "cross-site duplicate". The only thing that should be avoided is the same question asked by the same user on different sites.

– terdon
Mar 24 '14 at 17:52










9 Answers
9






active

oldest

votes


















82














To read variables from a file we can use the source or . command.



Lets assume the file contains the following line



MYVARIABLE="Any string"


we can then import this variable using



#!/bin/bash

source <filename>
echo $MYVARIABLE





share|improve this answer





















  • 15





    One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf /, which could be very dangerous.

    – Mark Ribau
    Jan 10 '15 at 2:57






  • 3





    Late to the party, but, no, it doesn't deserve to be marked up OR as the answer. This sources another bash source file which is NOT what the OP asked for. He asked how to read the contents of a FILE into a variable. NOT how to execute another script which sets a variable. The correct answer is the one below. name=$(cat "$file") .

    – RichieHH
    Nov 24 '15 at 12:54






  • 1





    OTOH, it is the answer to the question I asked google and google brought me here. Weird times, eh?

    – Michael Terry
    Jul 10 '17 at 18:04








  • 1





    Great also works for multiple variables! Point of @MarkRibau is understood but I guess that if you right the file in a different script and just have to pass it over its fine and controlled.

    – madlymad
    Jul 19 '17 at 11:25








  • 1





    You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh. Whatever you import in the function will only be available in that function. Note that it assumes global_variables.sh only contains one variable per line.

    – Nux
    Jun 14 '18 at 11:46



















49














Considering that you want all the content of your text file to be kept in your variable, you can use:



#!/bin/bash

file="/path/to/filename" #the file where you keep your string name

name=$(cat "$file") #the output of 'cat $file' is assigned to the $name variable

echo $name #test


Or, in pure bash:



#!/bin/bash

file="/path/to/filename" #the file where you keep your string name

read -d $'x04' name < "$file" #the content of $file is redirected to stdin from where it is read out into the $name variable

echo $name #test





share|improve this answer


























  • I dont want to display the variable, I want that this variable should be read by the script for further processing. I have tried awk which reads line by line.

    – user208413
    Oct 28 '13 at 8:48








  • 1





    Ok, delete echo $name . I use it just for test. Next you can use $name variable for further processing anywhere you want in your script.

    – Radu Rădeanu
    Oct 28 '13 at 8:51













  • I cant use it anywhere it my script because dhe script doesn't know the value of the variable. In our case the variable name.

    – user208413
    Oct 28 '13 at 9:28






  • 6





    @user208413 The value of $name variable is the string from your file assigned using cat $file command. What is not clear or so difficult to understand?

    – Radu Rădeanu
    Oct 28 '13 at 9:36








  • 1





    It's redundant to use a seperate $file variable if you're only using it once to load the $name variable, just use cat /path/to/file

    – kiri
    Oct 28 '13 at 10:05



















9














From within your script you can do this:



read name < file_containing _the_answer


You can even do this multiple times e.g. in a loop



while read LINE; do echo "$LINE"; done < file_containing_multiple_lines





share|improve this answer
























  • or for a file with multiple items on each line . . . grep -v ^# file |while read a b c; do echo a=$a b=$b c=$c; done

    – gaoithe
    Sep 1 '15 at 14:29



















6














One alternative way to do this would be to just redirect standard input to your file, where you have all the user input in the order it's expected by the program. For example, with the program (called script.sh)



#!/bin/bash
echo "Enter your name:"
read name
echo "...and now your age:"
read age

# example of how to use the values now stored in variables $name and $age
echo "Hello $name. You're $age years old, right?"


and the input file (called input.in)



Tomas
26


you could run this from the terminal in one of the following two ways:



$ cat input.in | ./script.sh
$ ./script.sh < input.in


and it would be equivalent to just running the script and entering the data manually - it would print the line "Hello Tomas. You're 26 years old, right?".



As Radu Rădeanu has already suggested, you could use cat inside your script to read the contents of a file into a avariable - in that case, you need each file to contain only one line, with only the value you want for that specific variable. In the above example, you'd split the input file into one with the name (say, name.in) and one with the age (say, age.in), and change the read name and read age lines to name=$(cat name.in) and age=$(cat age.in) respectively.






share|improve this answer


























  • I have the following script: vh = awk "NR==3{print;exit}" /var/www/test/test.txt with this I read line 3 from text file named test.txt. Once i get a string I want to use this string as an input for creating a directory

    – user208413
    Oct 28 '13 at 10:18








  • 1





    Change that to vh=$(awk "NR==3 {print;exit}" /var/www/test.txt). You will then have the string saved in variable $vh, so you can use it like so: mkdir "/var/www/$vh" - this will create a folder with the specified name inside /var/www.

    – Tomas Aschan
    Oct 28 '13 at 11:09











  • I have done this way but it still cant create the folder :(

    – user208413
    Oct 28 '13 at 11:34











  • @user208413: What error message(s) do you get? "It doesn't work" is, unfortunately, not a very helpful problem description...

    – Tomas Aschan
    Oct 29 '13 at 11:02



















2














Short answer:



name=`cat "$file"`





share|improve this answer































    2














    I found working solution here:
    https://af-design.com/2009/07/07/loading-data-into-bash-variables/



    if [ -f $SETTINGS_FILE ];then
    . $SETTINGS_FILE
    fi





    share|improve this answer
























    • The slides are no longer available.

      – kris
      Mar 12 '18 at 15:34





















    0














    If you want to use multiple strings, you could go with:



    path="/foo/bar";
    for p in `cat "$path"`;
    do echo "$p" ....... (here you would pipe it where you need it)


    OR



    If you want the user to indicate the file



    read -e "Specify path to variable(s): " path;
    for p in 'cat "$path"';
    do echo "$p" ............................





    share|improve this answer































      0














      name=$(<"$file") 


      From man bash:1785, this command substitution is equivalent to name=$(cat "$file") but faster.






      share|improve this answer

































        0














        #! /bin/bash
        # (GPL3+) Alberto Salvia Novella (es20490446e)


        variableInFile () {
        variable=${1}
        file=${2}

        source ${file}
        eval value=${${variable}}
        echo ${value}
        }


        variableInFile ${@}





        share|improve this answer























          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "89"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f367136%2fhow-do-i-read-a-variable-from-a-file%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          9 Answers
          9






          active

          oldest

          votes








          9 Answers
          9






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          82














          To read variables from a file we can use the source or . command.



          Lets assume the file contains the following line



          MYVARIABLE="Any string"


          we can then import this variable using



          #!/bin/bash

          source <filename>
          echo $MYVARIABLE





          share|improve this answer





















          • 15





            One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf /, which could be very dangerous.

            – Mark Ribau
            Jan 10 '15 at 2:57






          • 3





            Late to the party, but, no, it doesn't deserve to be marked up OR as the answer. This sources another bash source file which is NOT what the OP asked for. He asked how to read the contents of a FILE into a variable. NOT how to execute another script which sets a variable. The correct answer is the one below. name=$(cat "$file") .

            – RichieHH
            Nov 24 '15 at 12:54






          • 1





            OTOH, it is the answer to the question I asked google and google brought me here. Weird times, eh?

            – Michael Terry
            Jul 10 '17 at 18:04








          • 1





            Great also works for multiple variables! Point of @MarkRibau is understood but I guess that if you right the file in a different script and just have to pass it over its fine and controlled.

            – madlymad
            Jul 19 '17 at 11:25








          • 1





            You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh. Whatever you import in the function will only be available in that function. Note that it assumes global_variables.sh only contains one variable per line.

            – Nux
            Jun 14 '18 at 11:46
















          82














          To read variables from a file we can use the source or . command.



          Lets assume the file contains the following line



          MYVARIABLE="Any string"


          we can then import this variable using



          #!/bin/bash

          source <filename>
          echo $MYVARIABLE





          share|improve this answer





















          • 15





            One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf /, which could be very dangerous.

            – Mark Ribau
            Jan 10 '15 at 2:57






          • 3





            Late to the party, but, no, it doesn't deserve to be marked up OR as the answer. This sources another bash source file which is NOT what the OP asked for. He asked how to read the contents of a FILE into a variable. NOT how to execute another script which sets a variable. The correct answer is the one below. name=$(cat "$file") .

            – RichieHH
            Nov 24 '15 at 12:54






          • 1





            OTOH, it is the answer to the question I asked google and google brought me here. Weird times, eh?

            – Michael Terry
            Jul 10 '17 at 18:04








          • 1





            Great also works for multiple variables! Point of @MarkRibau is understood but I guess that if you right the file in a different script and just have to pass it over its fine and controlled.

            – madlymad
            Jul 19 '17 at 11:25








          • 1





            You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh. Whatever you import in the function will only be available in that function. Note that it assumes global_variables.sh only contains one variable per line.

            – Nux
            Jun 14 '18 at 11:46














          82












          82








          82







          To read variables from a file we can use the source or . command.



          Lets assume the file contains the following line



          MYVARIABLE="Any string"


          we can then import this variable using



          #!/bin/bash

          source <filename>
          echo $MYVARIABLE





          share|improve this answer















          To read variables from a file we can use the source or . command.



          Lets assume the file contains the following line



          MYVARIABLE="Any string"


          we can then import this variable using



          #!/bin/bash

          source <filename>
          echo $MYVARIABLE






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 11 '18 at 2:29









          mook765

          4,24221333




          4,24221333










          answered Oct 28 '13 at 9:44









          TakkatTakkat

          108k35249377




          108k35249377








          • 15





            One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf /, which could be very dangerous.

            – Mark Ribau
            Jan 10 '15 at 2:57






          • 3





            Late to the party, but, no, it doesn't deserve to be marked up OR as the answer. This sources another bash source file which is NOT what the OP asked for. He asked how to read the contents of a FILE into a variable. NOT how to execute another script which sets a variable. The correct answer is the one below. name=$(cat "$file") .

            – RichieHH
            Nov 24 '15 at 12:54






          • 1





            OTOH, it is the answer to the question I asked google and google brought me here. Weird times, eh?

            – Michael Terry
            Jul 10 '17 at 18:04








          • 1





            Great also works for multiple variables! Point of @MarkRibau is understood but I guess that if you right the file in a different script and just have to pass it over its fine and controlled.

            – madlymad
            Jul 19 '17 at 11:25








          • 1





            You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh. Whatever you import in the function will only be available in that function. Note that it assumes global_variables.sh only contains one variable per line.

            – Nux
            Jun 14 '18 at 11:46














          • 15





            One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf /, which could be very dangerous.

            – Mark Ribau
            Jan 10 '15 at 2:57






          • 3





            Late to the party, but, no, it doesn't deserve to be marked up OR as the answer. This sources another bash source file which is NOT what the OP asked for. He asked how to read the contents of a FILE into a variable. NOT how to execute another script which sets a variable. The correct answer is the one below. name=$(cat "$file") .

            – RichieHH
            Nov 24 '15 at 12:54






          • 1





            OTOH, it is the answer to the question I asked google and google brought me here. Weird times, eh?

            – Michael Terry
            Jul 10 '17 at 18:04








          • 1





            Great also works for multiple variables! Point of @MarkRibau is understood but I guess that if you right the file in a different script and just have to pass it over its fine and controlled.

            – madlymad
            Jul 19 '17 at 11:25








          • 1





            You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh. Whatever you import in the function will only be available in that function. Note that it assumes global_variables.sh only contains one variable per line.

            – Nux
            Jun 14 '18 at 11:46








          15




          15





          One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf /, which could be very dangerous.

          – Mark Ribau
          Jan 10 '15 at 2:57





          One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf /, which could be very dangerous.

          – Mark Ribau
          Jan 10 '15 at 2:57




          3




          3





          Late to the party, but, no, it doesn't deserve to be marked up OR as the answer. This sources another bash source file which is NOT what the OP asked for. He asked how to read the contents of a FILE into a variable. NOT how to execute another script which sets a variable. The correct answer is the one below. name=$(cat "$file") .

          – RichieHH
          Nov 24 '15 at 12:54





          Late to the party, but, no, it doesn't deserve to be marked up OR as the answer. This sources another bash source file which is NOT what the OP asked for. He asked how to read the contents of a FILE into a variable. NOT how to execute another script which sets a variable. The correct answer is the one below. name=$(cat "$file") .

          – RichieHH
          Nov 24 '15 at 12:54




          1




          1





          OTOH, it is the answer to the question I asked google and google brought me here. Weird times, eh?

          – Michael Terry
          Jul 10 '17 at 18:04







          OTOH, it is the answer to the question I asked google and google brought me here. Weird times, eh?

          – Michael Terry
          Jul 10 '17 at 18:04






          1




          1





          Great also works for multiple variables! Point of @MarkRibau is understood but I guess that if you right the file in a different script and just have to pass it over its fine and controlled.

          – madlymad
          Jul 19 '17 at 11:25







          Great also works for multiple variables! Point of @MarkRibau is understood but I guess that if you right the file in a different script and just have to pass it over its fine and controlled.

          – madlymad
          Jul 19 '17 at 11:25






          1




          1





          You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh. Whatever you import in the function will only be available in that function. Note that it assumes global_variables.sh only contains one variable per line.

          – Nux
          Jun 14 '18 at 11:46





          You can use sed to add local keyword and make the script a bit safer and not polute your global scope. So inside a a function do cat global_variables.sh | sed -e 's/^/local /' > local_variables.sh and then use . ./local_variables.sh. Whatever you import in the function will only be available in that function. Note that it assumes global_variables.sh only contains one variable per line.

          – Nux
          Jun 14 '18 at 11:46













          49














          Considering that you want all the content of your text file to be kept in your variable, you can use:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          name=$(cat "$file") #the output of 'cat $file' is assigned to the $name variable

          echo $name #test


          Or, in pure bash:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          read -d $'x04' name < "$file" #the content of $file is redirected to stdin from where it is read out into the $name variable

          echo $name #test





          share|improve this answer


























          • I dont want to display the variable, I want that this variable should be read by the script for further processing. I have tried awk which reads line by line.

            – user208413
            Oct 28 '13 at 8:48








          • 1





            Ok, delete echo $name . I use it just for test. Next you can use $name variable for further processing anywhere you want in your script.

            – Radu Rădeanu
            Oct 28 '13 at 8:51













          • I cant use it anywhere it my script because dhe script doesn't know the value of the variable. In our case the variable name.

            – user208413
            Oct 28 '13 at 9:28






          • 6





            @user208413 The value of $name variable is the string from your file assigned using cat $file command. What is not clear or so difficult to understand?

            – Radu Rădeanu
            Oct 28 '13 at 9:36








          • 1





            It's redundant to use a seperate $file variable if you're only using it once to load the $name variable, just use cat /path/to/file

            – kiri
            Oct 28 '13 at 10:05
















          49














          Considering that you want all the content of your text file to be kept in your variable, you can use:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          name=$(cat "$file") #the output of 'cat $file' is assigned to the $name variable

          echo $name #test


          Or, in pure bash:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          read -d $'x04' name < "$file" #the content of $file is redirected to stdin from where it is read out into the $name variable

          echo $name #test





          share|improve this answer


























          • I dont want to display the variable, I want that this variable should be read by the script for further processing. I have tried awk which reads line by line.

            – user208413
            Oct 28 '13 at 8:48








          • 1





            Ok, delete echo $name . I use it just for test. Next you can use $name variable for further processing anywhere you want in your script.

            – Radu Rădeanu
            Oct 28 '13 at 8:51













          • I cant use it anywhere it my script because dhe script doesn't know the value of the variable. In our case the variable name.

            – user208413
            Oct 28 '13 at 9:28






          • 6





            @user208413 The value of $name variable is the string from your file assigned using cat $file command. What is not clear or so difficult to understand?

            – Radu Rădeanu
            Oct 28 '13 at 9:36








          • 1





            It's redundant to use a seperate $file variable if you're only using it once to load the $name variable, just use cat /path/to/file

            – kiri
            Oct 28 '13 at 10:05














          49












          49








          49







          Considering that you want all the content of your text file to be kept in your variable, you can use:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          name=$(cat "$file") #the output of 'cat $file' is assigned to the $name variable

          echo $name #test


          Or, in pure bash:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          read -d $'x04' name < "$file" #the content of $file is redirected to stdin from where it is read out into the $name variable

          echo $name #test





          share|improve this answer















          Considering that you want all the content of your text file to be kept in your variable, you can use:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          name=$(cat "$file") #the output of 'cat $file' is assigned to the $name variable

          echo $name #test


          Or, in pure bash:



          #!/bin/bash

          file="/path/to/filename" #the file where you keep your string name

          read -d $'x04' name < "$file" #the content of $file is redirected to stdin from where it is read out into the $name variable

          echo $name #test






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 8 '15 at 11:49









          muru

          1




          1










          answered Oct 28 '13 at 8:44









          Radu RădeanuRadu Rădeanu

          118k35250325




          118k35250325













          • I dont want to display the variable, I want that this variable should be read by the script for further processing. I have tried awk which reads line by line.

            – user208413
            Oct 28 '13 at 8:48








          • 1





            Ok, delete echo $name . I use it just for test. Next you can use $name variable for further processing anywhere you want in your script.

            – Radu Rădeanu
            Oct 28 '13 at 8:51













          • I cant use it anywhere it my script because dhe script doesn't know the value of the variable. In our case the variable name.

            – user208413
            Oct 28 '13 at 9:28






          • 6





            @user208413 The value of $name variable is the string from your file assigned using cat $file command. What is not clear or so difficult to understand?

            – Radu Rădeanu
            Oct 28 '13 at 9:36








          • 1





            It's redundant to use a seperate $file variable if you're only using it once to load the $name variable, just use cat /path/to/file

            – kiri
            Oct 28 '13 at 10:05



















          • I dont want to display the variable, I want that this variable should be read by the script for further processing. I have tried awk which reads line by line.

            – user208413
            Oct 28 '13 at 8:48








          • 1





            Ok, delete echo $name . I use it just for test. Next you can use $name variable for further processing anywhere you want in your script.

            – Radu Rădeanu
            Oct 28 '13 at 8:51













          • I cant use it anywhere it my script because dhe script doesn't know the value of the variable. In our case the variable name.

            – user208413
            Oct 28 '13 at 9:28






          • 6





            @user208413 The value of $name variable is the string from your file assigned using cat $file command. What is not clear or so difficult to understand?

            – Radu Rădeanu
            Oct 28 '13 at 9:36








          • 1





            It's redundant to use a seperate $file variable if you're only using it once to load the $name variable, just use cat /path/to/file

            – kiri
            Oct 28 '13 at 10:05

















          I dont want to display the variable, I want that this variable should be read by the script for further processing. I have tried awk which reads line by line.

          – user208413
          Oct 28 '13 at 8:48







          I dont want to display the variable, I want that this variable should be read by the script for further processing. I have tried awk which reads line by line.

          – user208413
          Oct 28 '13 at 8:48






          1




          1





          Ok, delete echo $name . I use it just for test. Next you can use $name variable for further processing anywhere you want in your script.

          – Radu Rădeanu
          Oct 28 '13 at 8:51







          Ok, delete echo $name . I use it just for test. Next you can use $name variable for further processing anywhere you want in your script.

          – Radu Rădeanu
          Oct 28 '13 at 8:51















          I cant use it anywhere it my script because dhe script doesn't know the value of the variable. In our case the variable name.

          – user208413
          Oct 28 '13 at 9:28





          I cant use it anywhere it my script because dhe script doesn't know the value of the variable. In our case the variable name.

          – user208413
          Oct 28 '13 at 9:28




          6




          6





          @user208413 The value of $name variable is the string from your file assigned using cat $file command. What is not clear or so difficult to understand?

          – Radu Rădeanu
          Oct 28 '13 at 9:36







          @user208413 The value of $name variable is the string from your file assigned using cat $file command. What is not clear or so difficult to understand?

          – Radu Rădeanu
          Oct 28 '13 at 9:36






          1




          1





          It's redundant to use a seperate $file variable if you're only using it once to load the $name variable, just use cat /path/to/file

          – kiri
          Oct 28 '13 at 10:05





          It's redundant to use a seperate $file variable if you're only using it once to load the $name variable, just use cat /path/to/file

          – kiri
          Oct 28 '13 at 10:05











          9














          From within your script you can do this:



          read name < file_containing _the_answer


          You can even do this multiple times e.g. in a loop



          while read LINE; do echo "$LINE"; done < file_containing_multiple_lines





          share|improve this answer
























          • or for a file with multiple items on each line . . . grep -v ^# file |while read a b c; do echo a=$a b=$b c=$c; done

            – gaoithe
            Sep 1 '15 at 14:29
















          9














          From within your script you can do this:



          read name < file_containing _the_answer


          You can even do this multiple times e.g. in a loop



          while read LINE; do echo "$LINE"; done < file_containing_multiple_lines





          share|improve this answer
























          • or for a file with multiple items on each line . . . grep -v ^# file |while read a b c; do echo a=$a b=$b c=$c; done

            – gaoithe
            Sep 1 '15 at 14:29














          9












          9








          9







          From within your script you can do this:



          read name < file_containing _the_answer


          You can even do this multiple times e.g. in a loop



          while read LINE; do echo "$LINE"; done < file_containing_multiple_lines





          share|improve this answer













          From within your script you can do this:



          read name < file_containing _the_answer


          You can even do this multiple times e.g. in a loop



          while read LINE; do echo "$LINE"; done < file_containing_multiple_lines






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Oct 28 '13 at 22:35









          thomthom

          4,80731624




          4,80731624













          • or for a file with multiple items on each line . . . grep -v ^# file |while read a b c; do echo a=$a b=$b c=$c; done

            – gaoithe
            Sep 1 '15 at 14:29



















          • or for a file with multiple items on each line . . . grep -v ^# file |while read a b c; do echo a=$a b=$b c=$c; done

            – gaoithe
            Sep 1 '15 at 14:29

















          or for a file with multiple items on each line . . . grep -v ^# file |while read a b c; do echo a=$a b=$b c=$c; done

          – gaoithe
          Sep 1 '15 at 14:29





          or for a file with multiple items on each line . . . grep -v ^# file |while read a b c; do echo a=$a b=$b c=$c; done

          – gaoithe
          Sep 1 '15 at 14:29











          6














          One alternative way to do this would be to just redirect standard input to your file, where you have all the user input in the order it's expected by the program. For example, with the program (called script.sh)



          #!/bin/bash
          echo "Enter your name:"
          read name
          echo "...and now your age:"
          read age

          # example of how to use the values now stored in variables $name and $age
          echo "Hello $name. You're $age years old, right?"


          and the input file (called input.in)



          Tomas
          26


          you could run this from the terminal in one of the following two ways:



          $ cat input.in | ./script.sh
          $ ./script.sh < input.in


          and it would be equivalent to just running the script and entering the data manually - it would print the line "Hello Tomas. You're 26 years old, right?".



          As Radu Rădeanu has already suggested, you could use cat inside your script to read the contents of a file into a avariable - in that case, you need each file to contain only one line, with only the value you want for that specific variable. In the above example, you'd split the input file into one with the name (say, name.in) and one with the age (say, age.in), and change the read name and read age lines to name=$(cat name.in) and age=$(cat age.in) respectively.






          share|improve this answer


























          • I have the following script: vh = awk "NR==3{print;exit}" /var/www/test/test.txt with this I read line 3 from text file named test.txt. Once i get a string I want to use this string as an input for creating a directory

            – user208413
            Oct 28 '13 at 10:18








          • 1





            Change that to vh=$(awk "NR==3 {print;exit}" /var/www/test.txt). You will then have the string saved in variable $vh, so you can use it like so: mkdir "/var/www/$vh" - this will create a folder with the specified name inside /var/www.

            – Tomas Aschan
            Oct 28 '13 at 11:09











          • I have done this way but it still cant create the folder :(

            – user208413
            Oct 28 '13 at 11:34











          • @user208413: What error message(s) do you get? "It doesn't work" is, unfortunately, not a very helpful problem description...

            – Tomas Aschan
            Oct 29 '13 at 11:02
















          6














          One alternative way to do this would be to just redirect standard input to your file, where you have all the user input in the order it's expected by the program. For example, with the program (called script.sh)



          #!/bin/bash
          echo "Enter your name:"
          read name
          echo "...and now your age:"
          read age

          # example of how to use the values now stored in variables $name and $age
          echo "Hello $name. You're $age years old, right?"


          and the input file (called input.in)



          Tomas
          26


          you could run this from the terminal in one of the following two ways:



          $ cat input.in | ./script.sh
          $ ./script.sh < input.in


          and it would be equivalent to just running the script and entering the data manually - it would print the line "Hello Tomas. You're 26 years old, right?".



          As Radu Rădeanu has already suggested, you could use cat inside your script to read the contents of a file into a avariable - in that case, you need each file to contain only one line, with only the value you want for that specific variable. In the above example, you'd split the input file into one with the name (say, name.in) and one with the age (say, age.in), and change the read name and read age lines to name=$(cat name.in) and age=$(cat age.in) respectively.






          share|improve this answer


























          • I have the following script: vh = awk "NR==3{print;exit}" /var/www/test/test.txt with this I read line 3 from text file named test.txt. Once i get a string I want to use this string as an input for creating a directory

            – user208413
            Oct 28 '13 at 10:18








          • 1





            Change that to vh=$(awk "NR==3 {print;exit}" /var/www/test.txt). You will then have the string saved in variable $vh, so you can use it like so: mkdir "/var/www/$vh" - this will create a folder with the specified name inside /var/www.

            – Tomas Aschan
            Oct 28 '13 at 11:09











          • I have done this way but it still cant create the folder :(

            – user208413
            Oct 28 '13 at 11:34











          • @user208413: What error message(s) do you get? "It doesn't work" is, unfortunately, not a very helpful problem description...

            – Tomas Aschan
            Oct 29 '13 at 11:02














          6












          6








          6







          One alternative way to do this would be to just redirect standard input to your file, where you have all the user input in the order it's expected by the program. For example, with the program (called script.sh)



          #!/bin/bash
          echo "Enter your name:"
          read name
          echo "...and now your age:"
          read age

          # example of how to use the values now stored in variables $name and $age
          echo "Hello $name. You're $age years old, right?"


          and the input file (called input.in)



          Tomas
          26


          you could run this from the terminal in one of the following two ways:



          $ cat input.in | ./script.sh
          $ ./script.sh < input.in


          and it would be equivalent to just running the script and entering the data manually - it would print the line "Hello Tomas. You're 26 years old, right?".



          As Radu Rădeanu has already suggested, you could use cat inside your script to read the contents of a file into a avariable - in that case, you need each file to contain only one line, with only the value you want for that specific variable. In the above example, you'd split the input file into one with the name (say, name.in) and one with the age (say, age.in), and change the read name and read age lines to name=$(cat name.in) and age=$(cat age.in) respectively.






          share|improve this answer















          One alternative way to do this would be to just redirect standard input to your file, where you have all the user input in the order it's expected by the program. For example, with the program (called script.sh)



          #!/bin/bash
          echo "Enter your name:"
          read name
          echo "...and now your age:"
          read age

          # example of how to use the values now stored in variables $name and $age
          echo "Hello $name. You're $age years old, right?"


          and the input file (called input.in)



          Tomas
          26


          you could run this from the terminal in one of the following two ways:



          $ cat input.in | ./script.sh
          $ ./script.sh < input.in


          and it would be equivalent to just running the script and entering the data manually - it would print the line "Hello Tomas. You're 26 years old, right?".



          As Radu Rădeanu has already suggested, you could use cat inside your script to read the contents of a file into a avariable - in that case, you need each file to contain only one line, with only the value you want for that specific variable. In the above example, you'd split the input file into one with the name (say, name.in) and one with the age (say, age.in), and change the read name and read age lines to name=$(cat name.in) and age=$(cat age.in) respectively.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 13 '17 at 12:25









          Community

          1




          1










          answered Oct 28 '13 at 9:57









          Tomas AschanTomas Aschan

          1,40272854




          1,40272854













          • I have the following script: vh = awk "NR==3{print;exit}" /var/www/test/test.txt with this I read line 3 from text file named test.txt. Once i get a string I want to use this string as an input for creating a directory

            – user208413
            Oct 28 '13 at 10:18








          • 1





            Change that to vh=$(awk "NR==3 {print;exit}" /var/www/test.txt). You will then have the string saved in variable $vh, so you can use it like so: mkdir "/var/www/$vh" - this will create a folder with the specified name inside /var/www.

            – Tomas Aschan
            Oct 28 '13 at 11:09











          • I have done this way but it still cant create the folder :(

            – user208413
            Oct 28 '13 at 11:34











          • @user208413: What error message(s) do you get? "It doesn't work" is, unfortunately, not a very helpful problem description...

            – Tomas Aschan
            Oct 29 '13 at 11:02



















          • I have the following script: vh = awk "NR==3{print;exit}" /var/www/test/test.txt with this I read line 3 from text file named test.txt. Once i get a string I want to use this string as an input for creating a directory

            – user208413
            Oct 28 '13 at 10:18








          • 1





            Change that to vh=$(awk "NR==3 {print;exit}" /var/www/test.txt). You will then have the string saved in variable $vh, so you can use it like so: mkdir "/var/www/$vh" - this will create a folder with the specified name inside /var/www.

            – Tomas Aschan
            Oct 28 '13 at 11:09











          • I have done this way but it still cant create the folder :(

            – user208413
            Oct 28 '13 at 11:34











          • @user208413: What error message(s) do you get? "It doesn't work" is, unfortunately, not a very helpful problem description...

            – Tomas Aschan
            Oct 29 '13 at 11:02

















          I have the following script: vh = awk "NR==3{print;exit}" /var/www/test/test.txt with this I read line 3 from text file named test.txt. Once i get a string I want to use this string as an input for creating a directory

          – user208413
          Oct 28 '13 at 10:18







          I have the following script: vh = awk "NR==3{print;exit}" /var/www/test/test.txt with this I read line 3 from text file named test.txt. Once i get a string I want to use this string as an input for creating a directory

          – user208413
          Oct 28 '13 at 10:18






          1




          1





          Change that to vh=$(awk "NR==3 {print;exit}" /var/www/test.txt). You will then have the string saved in variable $vh, so you can use it like so: mkdir "/var/www/$vh" - this will create a folder with the specified name inside /var/www.

          – Tomas Aschan
          Oct 28 '13 at 11:09





          Change that to vh=$(awk "NR==3 {print;exit}" /var/www/test.txt). You will then have the string saved in variable $vh, so you can use it like so: mkdir "/var/www/$vh" - this will create a folder with the specified name inside /var/www.

          – Tomas Aschan
          Oct 28 '13 at 11:09













          I have done this way but it still cant create the folder :(

          – user208413
          Oct 28 '13 at 11:34





          I have done this way but it still cant create the folder :(

          – user208413
          Oct 28 '13 at 11:34













          @user208413: What error message(s) do you get? "It doesn't work" is, unfortunately, not a very helpful problem description...

          – Tomas Aschan
          Oct 29 '13 at 11:02





          @user208413: What error message(s) do you get? "It doesn't work" is, unfortunately, not a very helpful problem description...

          – Tomas Aschan
          Oct 29 '13 at 11:02











          2














          Short answer:



          name=`cat "$file"`





          share|improve this answer




























            2














            Short answer:



            name=`cat "$file"`





            share|improve this answer


























              2












              2








              2







              Short answer:



              name=`cat "$file"`





              share|improve this answer













              Short answer:



              name=`cat "$file"`






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 17 '15 at 14:53









              nedimnedim

              1234




              1234























                  2














                  I found working solution here:
                  https://af-design.com/2009/07/07/loading-data-into-bash-variables/



                  if [ -f $SETTINGS_FILE ];then
                  . $SETTINGS_FILE
                  fi





                  share|improve this answer
























                  • The slides are no longer available.

                    – kris
                    Mar 12 '18 at 15:34


















                  2














                  I found working solution here:
                  https://af-design.com/2009/07/07/loading-data-into-bash-variables/



                  if [ -f $SETTINGS_FILE ];then
                  . $SETTINGS_FILE
                  fi





                  share|improve this answer
























                  • The slides are no longer available.

                    – kris
                    Mar 12 '18 at 15:34
















                  2












                  2








                  2







                  I found working solution here:
                  https://af-design.com/2009/07/07/loading-data-into-bash-variables/



                  if [ -f $SETTINGS_FILE ];then
                  . $SETTINGS_FILE
                  fi





                  share|improve this answer













                  I found working solution here:
                  https://af-design.com/2009/07/07/loading-data-into-bash-variables/



                  if [ -f $SETTINGS_FILE ];then
                  . $SETTINGS_FILE
                  fi






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 24 '16 at 15:33









                  LukaszLukasz

                  1212




                  1212













                  • The slides are no longer available.

                    – kris
                    Mar 12 '18 at 15:34





















                  • The slides are no longer available.

                    – kris
                    Mar 12 '18 at 15:34



















                  The slides are no longer available.

                  – kris
                  Mar 12 '18 at 15:34







                  The slides are no longer available.

                  – kris
                  Mar 12 '18 at 15:34













                  0














                  If you want to use multiple strings, you could go with:



                  path="/foo/bar";
                  for p in `cat "$path"`;
                  do echo "$p" ....... (here you would pipe it where you need it)


                  OR



                  If you want the user to indicate the file



                  read -e "Specify path to variable(s): " path;
                  for p in 'cat "$path"';
                  do echo "$p" ............................





                  share|improve this answer




























                    0














                    If you want to use multiple strings, you could go with:



                    path="/foo/bar";
                    for p in `cat "$path"`;
                    do echo "$p" ....... (here you would pipe it where you need it)


                    OR



                    If you want the user to indicate the file



                    read -e "Specify path to variable(s): " path;
                    for p in 'cat "$path"';
                    do echo "$p" ............................





                    share|improve this answer


























                      0












                      0








                      0







                      If you want to use multiple strings, you could go with:



                      path="/foo/bar";
                      for p in `cat "$path"`;
                      do echo "$p" ....... (here you would pipe it where you need it)


                      OR



                      If you want the user to indicate the file



                      read -e "Specify path to variable(s): " path;
                      for p in 'cat "$path"';
                      do echo "$p" ............................





                      share|improve this answer













                      If you want to use multiple strings, you could go with:



                      path="/foo/bar";
                      for p in `cat "$path"`;
                      do echo "$p" ....... (here you would pipe it where you need it)


                      OR



                      If you want the user to indicate the file



                      read -e "Specify path to variable(s): " path;
                      for p in 'cat "$path"';
                      do echo "$p" ............................






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jun 10 '15 at 16:47









                      GeorgeGeorge

                      1




                      1























                          0














                          name=$(<"$file") 


                          From man bash:1785, this command substitution is equivalent to name=$(cat "$file") but faster.






                          share|improve this answer






























                            0














                            name=$(<"$file") 


                            From man bash:1785, this command substitution is equivalent to name=$(cat "$file") but faster.






                            share|improve this answer




























                              0












                              0








                              0







                              name=$(<"$file") 


                              From man bash:1785, this command substitution is equivalent to name=$(cat "$file") but faster.






                              share|improve this answer















                              name=$(<"$file") 


                              From man bash:1785, this command substitution is equivalent to name=$(cat "$file") but faster.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Oct 11 '18 at 0:42









                              abu_bua

                              3,45081227




                              3,45081227










                              answered Oct 10 '18 at 22:11









                              hellorkhellork

                              1011




                              1011























                                  0














                                  #! /bin/bash
                                  # (GPL3+) Alberto Salvia Novella (es20490446e)


                                  variableInFile () {
                                  variable=${1}
                                  file=${2}

                                  source ${file}
                                  eval value=${${variable}}
                                  echo ${value}
                                  }


                                  variableInFile ${@}





                                  share|improve this answer




























                                    0














                                    #! /bin/bash
                                    # (GPL3+) Alberto Salvia Novella (es20490446e)


                                    variableInFile () {
                                    variable=${1}
                                    file=${2}

                                    source ${file}
                                    eval value=${${variable}}
                                    echo ${value}
                                    }


                                    variableInFile ${@}





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      #! /bin/bash
                                      # (GPL3+) Alberto Salvia Novella (es20490446e)


                                      variableInFile () {
                                      variable=${1}
                                      file=${2}

                                      source ${file}
                                      eval value=${${variable}}
                                      echo ${value}
                                      }


                                      variableInFile ${@}





                                      share|improve this answer













                                      #! /bin/bash
                                      # (GPL3+) Alberto Salvia Novella (es20490446e)


                                      variableInFile () {
                                      variable=${1}
                                      file=${2}

                                      source ${file}
                                      eval value=${${variable}}
                                      echo ${value}
                                      }


                                      variableInFile ${@}






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 18 at 10:48









                                      Alberto Salvia NovellaAlberto Salvia Novella

                                      301112




                                      301112






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Ask Ubuntu!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f367136%2fhow-do-i-read-a-variable-from-a-file%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                                          ComboBox Display Member on multiple fields

                                          Is it possible to collect Nectar points via Trainline?