Find the answer to your Linux question:
Results 1 to 3 of 3
I have a text file that contains a single word and I want to write a bash script that will read the word from the text file... The following is ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Dec 2010
    Posts
    5

    reading a value from a textfile using bash script (beginner problem)


    I have a text file that contains a single word and I want to write a bash script that will read the word from the text file... The following is my incorrect attempt, as it assigns the name of the textfile to the variable as opposed to the word stored within the textfile:


    (assume I have a text file value.txt that has as its contents a single word, say wordone)

    #!/bin/sh
    for f in value.txt
    do
    echo $f
    done

    so the output of the above script is value.txt, however I want it to be wordone.
    to summarise: how do I assign the value of the word contained within a textfile to a variable?

  2. #2
    Just Joined!
    Join Date
    Jan 2010
    Posts
    40
    Yes, for-operator in BASH expects a list of string-values.
    Hence, "value.txt" is treated as the first and the only value in such list.

    Below I put some changes (in unified diff format -- it's easy to understand):

    Code:
     #!/bin/sh
    -for f in value.txt
    +for f in $(cat value.txt)
     do
     echo $f
     done
    The change means we do not use "value.txt" as a string-list, but we rather output content the file (cat) and insert the result into the for-statement (into the place of dollar-sign + brackets).
    Last edited by saulius2; 06-11-2011 at 06:01 AM.

  3. #3
    Just Joined! wild at heart's Avatar
    Join Date
    Jul 2008
    Posts
    13
    Thanx to share this Info

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •