How to use the “for .. in” loop2019 Community Moderator ElectionBash- Help modify code for a custom output statementHow can I get this script to error exit based on result of for loop?How to use a for loop inside an echo statement which is used to print statements into another script in UNIXWhy not use backticks with for loopAppend a file or command at the end of the line of another filePrint variable inside loopRun the previous command until the answer is no [conditional script]bash share array in “for do () & wait” loopWhile Loop over a File returning command not foundCall of HandBrakeCLI within script breaks loop

A social experiment. What is the worst that can happen?

How to implement a feedback to keep the DC gain at zero for this conceptual passive filter?

Store Credit Card Information in Password Manager?

How to write values with uncertainty and units with brackets: (339+-14) m/s

Is preaching recommended or mandatory to a temple priest?

How to advoid Unknown field: MyJSON.number

The IT department bottlenecks progress. How should I handle this?

Why Shazam when there is already Superman?

Does a 'pending' US visa application constitute a denial?

How to explain what's wrong with this application of the chain rule?

Travelling outside the UK without a passport

Aragorn's "guise" in the Orthanc Stone

What will be next at the bottom row and why?

Are the IPv6 address space and IPv4 address space completely disjoint?

Why should universal income be universal?

Lowest total scrabble score

Why can Carol Danvers change her suit colours in the first place?

Why electric field inside a cavity of a non conducting not zero

Why is it that I can sometimes guess the next note?

Is (0,1] a closed or open set?

Is it better practice to read straight from sheet music rather than memorize it?

Does Doodling or Improvising on the Piano Have Any Benefits?

Why does the Sun have different day lengths, but not the gas giants?

What is this called? Old film camera viewer?



How to use the “for .. in” loop



2019 Community Moderator ElectionBash- Help modify code for a custom output statementHow can I get this script to error exit based on result of for loop?How to use a for loop inside an echo statement which is used to print statements into another script in UNIXWhy not use backticks with for loopAppend a file or command at the end of the line of another filePrint variable inside loopRun the previous command until the answer is no [conditional script]bash share array in “for do () & wait” loopWhile Loop over a File returning command not foundCall of HandBrakeCLI within script breaks loop










-1















#!/bin/bash

if [ ! $# -eq 2 ];
then echo "You have not inputted the correct amound of arguments.
usage: $0 file user
Where file is the file to search
and user is the user to find"
fi

if [ ! -e $1 ];
then echo "You have inputted an invalid filename.
usage: $ file user
Where file is the file to search
and user is the user to find"
fi

let count=0

for line in `cat $1`; do
count=`expr $count + 1`
if [ "$line" == "$2" ]; then
echo "$2 found on line: $count"
exit 0
else
echo "Would you like to insert this username? y/n"
read answer
answer=`echo $answer | tr [a-z] [A-Z]`

if [ "$answer" != "y" ]; then
cat "$answer" >> "/classlist.txt"
else
echo "That's fine. Program ending ..."
exit 0
fi
fi
done


my "for in" loop doesn't do what it should do. the loop should take data from the text file (btw the text file is just a list of names broken up by line breaks) and assign it to the variable "line." when the "for in" loop ends, it should reassign the "line" variable to the next line in the text file. However, this is not the case. the script only ever reads the first data entry in the text file. did I use the loop incorrectly?










share|improve this question
























  • Your script runs a loop over the "lines" in the file, and on each line, either exits (if $2 was found), or asks to insert the username. If you mean to look through the whole file before asking to add something, you'll have to move the adding part out of the loop. You might also want to fix the indentation of the code to better see how the different parts of logic are nested. That, and run the script through [shellcheck.net], it has a number of obsolete, nonstandard or otherwise bad constructs (including for line in $(cat $1) itself)

    – ilkkachu
    Mar 12 at 20:49















-1















#!/bin/bash

if [ ! $# -eq 2 ];
then echo "You have not inputted the correct amound of arguments.
usage: $0 file user
Where file is the file to search
and user is the user to find"
fi

if [ ! -e $1 ];
then echo "You have inputted an invalid filename.
usage: $ file user
Where file is the file to search
and user is the user to find"
fi

let count=0

for line in `cat $1`; do
count=`expr $count + 1`
if [ "$line" == "$2" ]; then
echo "$2 found on line: $count"
exit 0
else
echo "Would you like to insert this username? y/n"
read answer
answer=`echo $answer | tr [a-z] [A-Z]`

if [ "$answer" != "y" ]; then
cat "$answer" >> "/classlist.txt"
else
echo "That's fine. Program ending ..."
exit 0
fi
fi
done


my "for in" loop doesn't do what it should do. the loop should take data from the text file (btw the text file is just a list of names broken up by line breaks) and assign it to the variable "line." when the "for in" loop ends, it should reassign the "line" variable to the next line in the text file. However, this is not the case. the script only ever reads the first data entry in the text file. did I use the loop incorrectly?










share|improve this question
























  • Your script runs a loop over the "lines" in the file, and on each line, either exits (if $2 was found), or asks to insert the username. If you mean to look through the whole file before asking to add something, you'll have to move the adding part out of the loop. You might also want to fix the indentation of the code to better see how the different parts of logic are nested. That, and run the script through [shellcheck.net], it has a number of obsolete, nonstandard or otherwise bad constructs (including for line in $(cat $1) itself)

    – ilkkachu
    Mar 12 at 20:49













-1












-1








-1


0






#!/bin/bash

if [ ! $# -eq 2 ];
then echo "You have not inputted the correct amound of arguments.
usage: $0 file user
Where file is the file to search
and user is the user to find"
fi

if [ ! -e $1 ];
then echo "You have inputted an invalid filename.
usage: $ file user
Where file is the file to search
and user is the user to find"
fi

let count=0

for line in `cat $1`; do
count=`expr $count + 1`
if [ "$line" == "$2" ]; then
echo "$2 found on line: $count"
exit 0
else
echo "Would you like to insert this username? y/n"
read answer
answer=`echo $answer | tr [a-z] [A-Z]`

if [ "$answer" != "y" ]; then
cat "$answer" >> "/classlist.txt"
else
echo "That's fine. Program ending ..."
exit 0
fi
fi
done


my "for in" loop doesn't do what it should do. the loop should take data from the text file (btw the text file is just a list of names broken up by line breaks) and assign it to the variable "line." when the "for in" loop ends, it should reassign the "line" variable to the next line in the text file. However, this is not the case. the script only ever reads the first data entry in the text file. did I use the loop incorrectly?










share|improve this question
















#!/bin/bash

if [ ! $# -eq 2 ];
then echo "You have not inputted the correct amound of arguments.
usage: $0 file user
Where file is the file to search
and user is the user to find"
fi

if [ ! -e $1 ];
then echo "You have inputted an invalid filename.
usage: $ file user
Where file is the file to search
and user is the user to find"
fi

let count=0

for line in `cat $1`; do
count=`expr $count + 1`
if [ "$line" == "$2" ]; then
echo "$2 found on line: $count"
exit 0
else
echo "Would you like to insert this username? y/n"
read answer
answer=`echo $answer | tr [a-z] [A-Z]`

if [ "$answer" != "y" ]; then
cat "$answer" >> "/classlist.txt"
else
echo "That's fine. Program ending ..."
exit 0
fi
fi
done


my "for in" loop doesn't do what it should do. the loop should take data from the text file (btw the text file is just a list of names broken up by line breaks) and assign it to the variable "line." when the "for in" loop ends, it should reassign the "line" variable to the next line in the text file. However, this is not the case. the script only ever reads the first data entry in the text file. did I use the loop incorrectly?







linux bash shell-script






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 12 at 20:38









Rui F Ribeiro

41.6k1483141




41.6k1483141










asked Mar 12 at 20:37









JoshJosh

6




6












  • Your script runs a loop over the "lines" in the file, and on each line, either exits (if $2 was found), or asks to insert the username. If you mean to look through the whole file before asking to add something, you'll have to move the adding part out of the loop. You might also want to fix the indentation of the code to better see how the different parts of logic are nested. That, and run the script through [shellcheck.net], it has a number of obsolete, nonstandard or otherwise bad constructs (including for line in $(cat $1) itself)

    – ilkkachu
    Mar 12 at 20:49

















  • Your script runs a loop over the "lines" in the file, and on each line, either exits (if $2 was found), or asks to insert the username. If you mean to look through the whole file before asking to add something, you'll have to move the adding part out of the loop. You might also want to fix the indentation of the code to better see how the different parts of logic are nested. That, and run the script through [shellcheck.net], it has a number of obsolete, nonstandard or otherwise bad constructs (including for line in $(cat $1) itself)

    – ilkkachu
    Mar 12 at 20:49
















Your script runs a loop over the "lines" in the file, and on each line, either exits (if $2 was found), or asks to insert the username. If you mean to look through the whole file before asking to add something, you'll have to move the adding part out of the loop. You might also want to fix the indentation of the code to better see how the different parts of logic are nested. That, and run the script through [shellcheck.net], it has a number of obsolete, nonstandard or otherwise bad constructs (including for line in $(cat $1) itself)

– ilkkachu
Mar 12 at 20:49





Your script runs a loop over the "lines" in the file, and on each line, either exits (if $2 was found), or asks to insert the username. If you mean to look through the whole file before asking to add something, you'll have to move the adding part out of the loop. You might also want to fix the indentation of the code to better see how the different parts of logic are nested. That, and run the script through [shellcheck.net], it has a number of obsolete, nonstandard or otherwise bad constructs (including for line in $(cat $1) itself)

– ilkkachu
Mar 12 at 20:49










1 Answer
1






active

oldest

votes


















0














Short answer: Change your exit 0 to continue



To be sure your for loop is working correctly, you can do a short test:
count=0
for line in cat $1
do
count=expr $count + 1
echo $line
done
echo "Counted $count lines"



If that gives you all the lines in your file, and the accurate count, then your for loop is working correctly. (seems correct. Not the acceptable standard, but I prefer this format myself)



The first issue is, this:
if [ "$line" == "$2" ]; then
echo "$2 found on line: $count"
exit 0

The exit 0 says exit the script (i.e. do nothing more.)
You could just eliminate this line all together as it will drop out of the if and hit the done which will read the next line. Or you could change it to continue which will return to the top of the loop and read the next line.



The second issue is:
if [ "$answer" != "y" ]; then
cat "$answer" >> "/classlist.txt"
else
echo "That's fine. Program ending ..."
exit 0
fi

If you really want to exit the script, your exit 0 is fine. If you want to break out of the loop, then this should be a break. If you want to go to the top of the loop to read the next line, it should be a continue.



To see how the different ways of exiting the loop affect your code, add the line echo "Finished loop" to the end of your script. Experiment with the break, continue, and exit 0 options to see which one prints "Finished Loop"






share|improve this answer






















    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "106"
    ;
    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: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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%2funix.stackexchange.com%2fquestions%2f505958%2fhow-to-use-the-for-in-loop%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Short answer: Change your exit 0 to continue



    To be sure your for loop is working correctly, you can do a short test:
    count=0
    for line in cat $1
    do
    count=expr $count + 1
    echo $line
    done
    echo "Counted $count lines"



    If that gives you all the lines in your file, and the accurate count, then your for loop is working correctly. (seems correct. Not the acceptable standard, but I prefer this format myself)



    The first issue is, this:
    if [ "$line" == "$2" ]; then
    echo "$2 found on line: $count"
    exit 0

    The exit 0 says exit the script (i.e. do nothing more.)
    You could just eliminate this line all together as it will drop out of the if and hit the done which will read the next line. Or you could change it to continue which will return to the top of the loop and read the next line.



    The second issue is:
    if [ "$answer" != "y" ]; then
    cat "$answer" >> "/classlist.txt"
    else
    echo "That's fine. Program ending ..."
    exit 0
    fi

    If you really want to exit the script, your exit 0 is fine. If you want to break out of the loop, then this should be a break. If you want to go to the top of the loop to read the next line, it should be a continue.



    To see how the different ways of exiting the loop affect your code, add the line echo "Finished loop" to the end of your script. Experiment with the break, continue, and exit 0 options to see which one prints "Finished Loop"






    share|improve this answer



























      0














      Short answer: Change your exit 0 to continue



      To be sure your for loop is working correctly, you can do a short test:
      count=0
      for line in cat $1
      do
      count=expr $count + 1
      echo $line
      done
      echo "Counted $count lines"



      If that gives you all the lines in your file, and the accurate count, then your for loop is working correctly. (seems correct. Not the acceptable standard, but I prefer this format myself)



      The first issue is, this:
      if [ "$line" == "$2" ]; then
      echo "$2 found on line: $count"
      exit 0

      The exit 0 says exit the script (i.e. do nothing more.)
      You could just eliminate this line all together as it will drop out of the if and hit the done which will read the next line. Or you could change it to continue which will return to the top of the loop and read the next line.



      The second issue is:
      if [ "$answer" != "y" ]; then
      cat "$answer" >> "/classlist.txt"
      else
      echo "That's fine. Program ending ..."
      exit 0
      fi

      If you really want to exit the script, your exit 0 is fine. If you want to break out of the loop, then this should be a break. If you want to go to the top of the loop to read the next line, it should be a continue.



      To see how the different ways of exiting the loop affect your code, add the line echo "Finished loop" to the end of your script. Experiment with the break, continue, and exit 0 options to see which one prints "Finished Loop"






      share|improve this answer

























        0












        0








        0







        Short answer: Change your exit 0 to continue



        To be sure your for loop is working correctly, you can do a short test:
        count=0
        for line in cat $1
        do
        count=expr $count + 1
        echo $line
        done
        echo "Counted $count lines"



        If that gives you all the lines in your file, and the accurate count, then your for loop is working correctly. (seems correct. Not the acceptable standard, but I prefer this format myself)



        The first issue is, this:
        if [ "$line" == "$2" ]; then
        echo "$2 found on line: $count"
        exit 0

        The exit 0 says exit the script (i.e. do nothing more.)
        You could just eliminate this line all together as it will drop out of the if and hit the done which will read the next line. Or you could change it to continue which will return to the top of the loop and read the next line.



        The second issue is:
        if [ "$answer" != "y" ]; then
        cat "$answer" >> "/classlist.txt"
        else
        echo "That's fine. Program ending ..."
        exit 0
        fi

        If you really want to exit the script, your exit 0 is fine. If you want to break out of the loop, then this should be a break. If you want to go to the top of the loop to read the next line, it should be a continue.



        To see how the different ways of exiting the loop affect your code, add the line echo "Finished loop" to the end of your script. Experiment with the break, continue, and exit 0 options to see which one prints "Finished Loop"






        share|improve this answer













        Short answer: Change your exit 0 to continue



        To be sure your for loop is working correctly, you can do a short test:
        count=0
        for line in cat $1
        do
        count=expr $count + 1
        echo $line
        done
        echo "Counted $count lines"



        If that gives you all the lines in your file, and the accurate count, then your for loop is working correctly. (seems correct. Not the acceptable standard, but I prefer this format myself)



        The first issue is, this:
        if [ "$line" == "$2" ]; then
        echo "$2 found on line: $count"
        exit 0

        The exit 0 says exit the script (i.e. do nothing more.)
        You could just eliminate this line all together as it will drop out of the if and hit the done which will read the next line. Or you could change it to continue which will return to the top of the loop and read the next line.



        The second issue is:
        if [ "$answer" != "y" ]; then
        cat "$answer" >> "/classlist.txt"
        else
        echo "That's fine. Program ending ..."
        exit 0
        fi

        If you really want to exit the script, your exit 0 is fine. If you want to break out of the loop, then this should be a break. If you want to go to the top of the loop to read the next line, it should be a continue.



        To see how the different ways of exiting the loop affect your code, add the line echo "Finished loop" to the end of your script. Experiment with the break, continue, and exit 0 options to see which one prints "Finished Loop"







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 13 at 2:48









        Scottie HScottie H

        676




        676



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • 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%2funix.stackexchange.com%2fquestions%2f505958%2fhow-to-use-the-for-in-loop%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







            -bash, linux, shell-script

            Popular posts from this blog

            Creating 100m^2 grid automatically using QGIS?Creating grid constrained within polygon in QGIS?Createing polygon layer from point data using QGIS?Creating vector grid using QGIS?Creating grid polygons from coordinates using R or PythonCreating grid from spatio temporal point data?Creating fields in attributes table using other layers using QGISCreate .shp vector grid in QGISQGIS Creating 4km point grid within polygonsCreate a vector grid over a raster layerVector Grid Creates just one grid

            What is this called? Old film camera viewer?What makes a good film camera?What to do with an old film camera?What should one look for when buying a used film camera?What is the value and age of this pre-1967 Ricoh 35 mm camera?DSLR recommendation, question about old Canon 35mm film Camera & lensesCan anyone identify the silver rangefinder-style camera in this advertisement?What kind of a Polaroid 600-camera is this?Will an old film camera still work even when not used in a very long time?What is this camera / Can I develop the film?How to fit an action camera into antique (bellows) housing?What to check when buying used and old film bodies?

            Why is this plane circling around the Lucknow airport every day?Why do aircraft on Flight Radar 24 jump around randomly sometimes?What airport has this walkway over a taxiway?How does Chicago O'Hare's tower sequence aircraft at peak capacity?Which airport is featured in this Delta commercial?After a crash, for how long is the airport closed?Can a passenger plane stand still in the air, or hover at a fixed location above a ground?What are those trucks towing around, and why?What is this airport outside of Cairo, Egypt?Which US airport has the lowest circling MDH?What is this airport video?