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 ...
- 05-14-2010 #1Just 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.
For some reason, all it does is display the source code when I call it. I've tried: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
/bin/sh ./first.sh
/bin/bash ./first.sh
and
chmod +x first.sh
./first.sh
What gives?
- 05-15-2010 #2Just 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:
*Only run it in the folder you wantCode: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
Hope it helps
- 05-15-2010 #3
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:
$0 contains the name of the script itself, so this would check if the file is the current script and skip over it.Code:for file in * do if [ "$(readlink -m "$0")" == "$(readlink -m "$file")" ] then continue fi if grep -q POSIX "$file" ...
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


Reply With Quote