Find the answer to your Linux question:
Results 1 to 3 of 3
I'm following along with a book. This is by bash script. Code: #!/bin/sh # first.sh # this file searches the current directory for the # string POSIX, then displays those ...
  1. #1
    Just Joined!
    Join Date
    May 2010
    Posts
    1

    The source of my bash script is printed instead of what was intended

    I'm following along with a book. This is by bash script.

    Code:
    #!/bin/sh
    
    # first.sh
    # this file searches the current directory for the 
    # string POSIX, then displays those files to the standard output
    
    for file in *
    do
     if grep -q POSIX $file
     then
      more $file
     fi
    done
    
    exit 0
    For some reason, all it does is display the source code when I call it. I've tried:

    /bin/sh ./first.sh

    /bin/bash ./first.sh

    and

    chmod +x first.sh
    ./first.sh

    What gives?

  2. #2
    Just Joined!
    Join Date
    May 2010
    Posts
    6
    Hi nolsen01,

    If you need to search all files containg string "POSIX" within current folder and its sub-folders you can try with:


    Code:
    1)
    find . | xargs grep -n "POSIX"
    This will print the file/s where the string "POSIX" is founded, the line number and 
    the text within line itself as follow:
    
    file name:line number: This is the line containing string "POSIX"
    
    2)
    find . | xargs grep -n "POSIX" | awk -F":" '{print $1,$2}'
    This script does the same, but only printing the file name and line number where the 
    string "POSIX" is founded, without text within line matched as follow.
    
    inputdile 25
    *Only run it in the folder you want

    Hope it helps

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    So to answer your question, let's look at what the script actually does.

    For every file in the current directory, it checks if the file contains the string "POSIX". Every such file is printed with the "more" command.

    Well, your script is obviously in the current directory. Does it contain the string "POSIX"? Yes it does. Therefore, the script will be printed.

    One way of getting around this problem would be to change the loop to the following:
    Code:
    for file in *
    do
        if [ "$(readlink -m "$0")" == "$(readlink -m "$file")" ]
        then
            continue
        fi
    
        if grep -q POSIX "$file"
    ...
    $0 contains the name of the script itself, so this would check if the file is the current script and skip over it.

    Of course, it may be that you want the file to be printed, since it obviously does contain the string "POSIX".
    DISTRO=Arch
    Registered Linux User #388732

Posting Permissions

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